SQL Server聚合/分组日期并将它们相加

问题描述 投票:0回答:2

一张卡片会在一天内多次滑动,我随身携带的数据是卡片编号和表格中的日期。我正在尝试创建一个用户定义的函数来聚合它们并显示新列中的滑动次数。

我将传递卡号作为输入。

我正在使用SQL Server 2012。

5678907 2017-06-11  
5678907 2017-06-11  
5678907 2017-06-11  
5678907 2017-06-14  
5678907 2017-06-15  

产量

5678907 2017-06-11  3  
5678907 2017-06-14  1  
5678907 2017-06-15  1    
sql sql-server tsql
2个回答
1
投票

只需使用带有聚合函数group bycount()子句

select Card, [date], count([date]) [Swipecount] from table
group by Card, [date]

0
投票

另一种方法是 -

SELECT DISTINCT 
[Card number],[Date],COUNT(*) OVER (PARTITION BY [Card number],[Date]) cnt
FROM yourtableName

如果您使用group by,请使用COUNT(*)。 COUNT(日期)/计数(列) - 忽略NULL值/,如果其中一个日期为NULL,则输出为0。

            SELECT [Card number],[Date],COUNT(*)  cnt
            FROM 
            (
                select 5678907 [Card number],'2017-06-11' [Date]  UNION ALL 
                select 5678907 ,'2017-06-11'   UNION ALL 
                select 5678907 ,'2017-06-11'   UNION ALL  
                select 5678907 ,'2017-06-14'   UNION ALL 
                select 5678907 ,NULL 
            )t
            GROUP BY [Card number],[Date]

            /*------------------------
            OUTPUT 
            ------------------------*/
            Card number Date       cnt
            ----------- ---------- -----------
            5678907     NULL       1
            5678907     2017-06-11 3
            5678907     2017-06-14 1

            (3 row(s) affected)
© www.soinside.com 2019 - 2024. All rights reserved.