2013-08-30 71 views
0

我試圖實現一個報告,將顯示所有的日常計數以及每週數在同一個表。我嘗試過不同的技術,但我似乎無法得到我想要的東西。如何顯示每週總數在一個表中

我想下面顯示出類似的表。

+-----------+-----+-------+--------+--+--+--+ 
| 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 | | | | 
+-----------+-----+-------+--------+--+--+--+ 

如果有一個現有的代碼或技術,我可以實現這樣的事情,請讓我。謝謝。

宣威

+0

您需要使用Row Number()和Over Partition By。請參閱以下鏈接尋求建議:http://www.codeproject.com/Articles/308281/How-to-Use-ROW_NUMBER-to-Enumerate-and-Partition-R – JsonStatham

回答

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 
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 
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

完整的示例0
+0

嗨感謝您的建議和答案,我高度欣賞它。但似乎我真的需要在新專欄上發表意見。由於某些要求,例如Average,Daily Min和Daily Max。 – Sherwin

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()) 
相關問題