如何在一个表中显示每周总计数

时间:2013-08-30 07:03:36

标签: sql-server sql-server-2008 tsql

我正在尝试创建一个报告,该报告将显示同一个表中的所有每日计数和每周计数。我尝试了不同的技术,但我似乎无法得到我想要的东西。

我试图在下面显示类似的表格。

+-----------+-----+-------+--------+--+--+--+
|  August   |     | Count |        |  |  |  |
+-----------+-----+-------+--------+--+--+--+
| 8/1/2013  | Thu | 1,967 |        |  |  |  |
| 8/2/2013  | Fri | 1,871 |        |  |  |  |
| 8/3/2013  | Sat | 1,950 |        |  |  |  |
| 8/4/2013  | Sun | 2,013 | 7801   |  |  |  |
| 8/5/2013  | Mon | 2,039 |        |  |  |  |
| 8/6/2013  | Tue | 1,871 |        |  |  |  |
| 8/7/2013  | Wed | 1,611 |        |  |  |  |
| 8/8/2013  | Thu | 1,680 |        |  |  |  |
| 8/9/2013  | Fri | 1,687 |        |  |  |  |
| 8/10/2013 | Sat | 1,649 |        |  |  |  |
| 8/11/2013 | Sun | 1,561 | 12,098 |  |  |  |
+-----------+-----+-------+--------+--+--+--+

如果现有的代码或技术可以实现这样的目的,请告诉我。感谢。

舍温

4 个答案:

答案 0 :(得分:2)

如果您不介意在新行而不是新列上使用这些小计,GROUP BY WITH ROLLUP可能是您的解决方案:

SET LANGUAGE GERMAN用于将星期一设置为一周的第一天,并允许我们总结到星期日

SET LANGUAGE GERMAN;

WITH first AS
(
  SELECT
    date,
    day,
    DATEPART(dw, date) AS dayweek,
    DATEPART(wk, date) AS week,
    count
  FROM example
)

SELECT
  CASE WHEN (GROUPING(dayweek) = 1) THEN 'TOT' ELSE CAST(MAX(date) AS VARCHAR(20)) END AS date,
  CASE WHEN (GROUPING(dayweek) = 1) THEN 'TOT' ELSE MAX(day) END AS day,
  SUM(count) AS count
FROM first
GROUP BY week,dayweek WITH ROLLUP

请参阅sqlfiddle

上的完整示例

答案 1 :(得分:2)

尝试类似这样的操作,但请务必检查服务器上的星期日是哪个WEEKDAY,因为可以修改。

select T1.August, T1.[Count], 
case DATEPART(WEEKDAY, O.Order_Date)
    WHEN 1 THEN (SELECT CONVERT(varchar(10), SUM(T2.[Count]) FROM TableName T2 WHERE T2.August BETWEEN DATEADD(d,-7,T1.August) and T1.August))
    ELSE ''
end as Weekly_Count
FROM TablleName T1
ORDER BY T.August

答案 2 :(得分:0)

如果使用存储过程,则创建一个临时表并使用游标循环,然后进行求和。 你也可以这样做:

SELECT CreatedDate, Amount, CASE WHEN DATENAME(dw , CreatedDate) = 'Sunday' THEN (SELECT SUM(Amount) FROM AmountTable at2 WHERE CreatedDate <= at1.CreatedDate AND CreatedDate > DATEADD(Day, -7, at1.CreatedDate)) ELSE 0 END AS 'WeekTotal'
from AmountTable at1

答案 3 :(得分:0)

沿着这些行的某些东西是否有效,语法可能不是100%

select
[Date],
DOW,
[Count],
Case When DOW = 'Mon' then 1 else 2 end as Partition_DOW,
SUM([Count]) OVER (PARTITION BY (Case When DOW = 'Mon' then 1 else 0 end) ORDER BY [Date]) AS 'Monthly_Total'
from My_table
where Month([Date]) = Month(Date()) AND Year([Date]) = Year(Date())