如何汇总给定周和每个工作日的总计?

时间:2016-09-26 21:08:05

标签: sql sql-server tsql count aggregate

我目前正在尝试构建逻辑,该逻辑将在报告运行的那一天独立地计算当周的每周的每一天。我需要弄清楚如何构建一个查询来将每天(以及每周总和)聚合为单独的列。

下面我只提供了我用于Total和Sunday的子查询:

DECLARE 
@SundayOfCurrentWeek date
, @MondayOfCurrentWeek  date
, @TuesdayOfCurrentWeek  date
, @WednesdayOfCurrentWeek date
, @ThursdayOfCurrentWeek date
, @FridayOfCurrentWeek date
, @SaturdayOfCurrentWeek date
set @SundayOfCurrentWeek = DATEADD(wk, DATEDIFF(wk,0,getdate()), -1)
set @MondayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 0) 
set @TuesdayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 1) 
set @WednesdayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 2) 
set @ThursdayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 3) 
set @FridayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 4) 
set @SaturdayOfCurrentWeek =  DATEADD(wk, DATEDIFF(wk,0,getdate()), 5)

/ **选择本周内的总记录数** /

( select count(*) 
from release 
where releasetime >= @SundayOfCurrentWeek 
AND releasetime <= @SaturdayOfCurrentWeek ) as TotalCount 

/ **从星期日起选择所有记录** /

( select count(*) as SundayCount
from release 
where releasetime >= @SundayOfCurrentWeek 
AND releasetime < @MondayOfCurrentWeek ) as SundayCount

2 个答案:

答案 0 :(得分:1)

;WITH cte AS (
    SELECT
       DATENAME(dw,releasetime) as DayOfWeekName
       ,COUNT(*) OVER () as TotalCount
    FROM
       @release
    WHERE
       releasetime >= DATEADD(DAY,- DATEPART(dw,GETDATE()) + 1,CAST(GETDATE() AS DATE)) 
       AND releasetime < DATEADD(DAY,7 - DATEPART(dw,GETDATE()) + 1,CAST(GETDATE() AS DATE))
)

SELECT *
FROM
    cte
    PIVOT (
       COUNT(DayOfWeekName)
       FOR DayOfWeekName IN (Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)
    ) p

有很多不同的方法。我假设您希望结果以星期几而不是行的形式显示在列中。所以我向您展示了一种透视结果的方法。您也可以在另一个答案中使用条件聚合。使用Pivot的技巧是先准备你想要的表然后使用公用表表达式[cte]进行数据透视。然后使用窗口函数,您可以轻松获得COUNT(*)总计数甚至运行计数。

TOTALCOUNT COUNT(*) OVER () - 注意没有分区,没有按语句排序只是简单地计算结果集。

运行计数可能如下所示:

COUNT(*) OVER (ORDER BY DATEPART(dw,releasetime))

绝对建议熟悉窗口功能!

编辑,更改了where语句中的Date比较。它将自动计算当周的星期日,然后是下周的星期日。下周星期日的原因是我将它从<=切换到<因为SQL Server将在23:59:59.997到00:00:00.000之间进行任何处理,第二天你要么必须做你的结束日期是星期六的午夜,如果发布时间有一个时间部分,或者你在第二天上午12点说出来并且说不到。

答案 1 :(得分:-1)

试试这个......

SELECT 
DATEPART(DW, [date_col]) AS 'Day_of_Week', 
COUNT(*) AS 'Count_per_Day'
FROM [Table]
GROUP BY DATEPART(DW, [date_col])

请注意,Day_of_Week = 1表示星期日,7表示星期六。