如何计算每个工作日(星期一,星期二等)的行计数总计(count(*))

时间:2018-06-21 18:24:25

标签: sql sql-server

我想知道如何计算按星期几分层的总行数

SELECT 
    OPERATOR,
   [Monday],
   [Tuesday] ,
   [Wednesday] ,
   [Thursday] ,
   [Friday] 
   COUNT(*) AS TOTAL -- i can not do this / HOW TO MAKE ?
FROM (
SELECT DISTINCT ID, 
           OPERATOR, 
           Datename(weekday, TAB_DATE) DAY
    FROM   #TABLES
    WHERE 
    TAB_DATE>=DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) 
    AND TAB_DATE<DATEADD(wk,1,DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)) and
    OPERATOR_ID IN (111,222,444)  GROUP BY ID,OPERATOR,TAB_DATE
    ) AS  p  
    PIVOT ( 
    COUNT (ID) 
    FOR DAY IN ( [Monday], [Tuesday], [Wednesday], [Thursday], [Friday]))  pvt  

2 个答案:

答案 0 :(得分:0)

将您在子查询中拥有的所有内容放入,然后添加每天的结果以得出总计:

SELECT
  *,
  [Monday] + [Tuesday] + [Wednesday] + [Thursday] + [Friday] AS TOTAL
FROM (
  SELECT 
     OPERATOR,
     [Monday], [Tuesday], [Wednesday], [Thursday], [Friday] 
  FROM (
    SELECT DISTINCT 
      ID, OPERATOR, Datename(weekday, TAB_DATE) DAY
    FROM #TABLES
    WHERE TAB_DATE>=DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) 
      AND TAB_DATE<DATEADD(wk,1,DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0))
      AND OPERATOR_ID IN (111,222,444)
    GROUP BY ID, OPERATOR, TAB_DATE
    ) AS  p  
    PIVOT ( 
    COUNT (ID) 
    FOR DAY IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday])
    ) pvt 
  ) t

我已经格式化了您的代码。

答案 1 :(得分:0)

如果我对您的理解正确,则可以使用OVER子句:

SELECT 
    OPERATOR,
   [Monday],
   [Tuesday] ,
   [Wednesday] ,
   [Thursday] ,
   [Friday],
   COUNT(*) OVER()
FROM (
SELECT DISTINCT ID, 
           OPERATOR, 
           Datename(weekday, TAB_DATE) DAY
    FROM   #TABLES
    WHERE 
    TAB_DATE>=DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) 
    AND TAB_DATE<DATEADD(wk,1,DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0)) and
    OPERATOR_ID IN (111,222,444)  GROUP BY ID,OPERATOR,TAB_DATE
    ) AS  p  
    PIVOT ( 
    COUNT (ID) 
    FOR DAY IN ( [Monday], [Tuesday], [Wednesday], [Thursday], [Friday]))  pvt