2013-04-11 145 views
1
CREATE TABLE Daily 
    ([DATE] datetime, [sales] int) 
; 

INSERT INTO Daily 
    ([DATE], [sales]) 
VALUES 
    ('2012-01-01 00:00:00', 1), 
    ('2012-01-02 00:00:00', 2), 
    ('2012-01-03 00:00:00', 3), 
    ('2012-01-04 00:00:00', 4), 
    ('2012-01-05 00:00:00', 5), 
    ('2012-01-06 00:00:00', 6), 
    ('2012-01-06 00:00:00', 5), 
    ('2012-01-07 00:00:00', 7), 
    ('2012-01-08 00:00:00', 8), 
    ('2012-01-09 00:00:00', 9), 
    ('2012-01-10 00:00:00', 10), 
    ('2012-01-11 00:00:00', 11), 
    ('2012-01-12 00:00:00', 12), 
    ('2012-01-13 00:00:00', 13), 
    ('2012-01-14 00:00:00', 14), 
    ('2012-01-15 00:00:00', 15), 
    ('2012-01-16 00:00:00', 16) 
; 

CREATE TABLE Weekly 
    ([Weekly] datetime) 
; 

INSERT INTO Weekly 
    ([Weekly]) 
VALUES 
    ('2012-01-07 00:00:00'), 
    ('2012-01-14 00:00:00'), 
    ('2012-01-21 00:00:00') 
; 

之前,我想最後的輸出和連接兩個表

Sales  
1/7/2012  33 
1/14/2012  77 

任何幫助,將不勝感激。在此先感謝

+2

對不起,你到底想達到什麼目的?這是哪個SQL? – Rob 2013-04-11 07:47:50

回答

1

我會強烈reccommend反對在表中存儲這一點,如果你的任何日常數據的改變你的每週數據將需要改變,否則將是錯誤的,而不是創建一個視圖如下:

CREATE VIEW Weekly 
AS 
    SELECT WeekEnd = DATEADD(WEEK, DATEDIFF(WEEK, 0, [DATE]) + 1, -2), 
      Sales = SUM(Sales) 
    FROM Daily 
    GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [DATE]) + 1, -2); 

您可以像創建表格一樣使用它,但這將始終與日常數據同步。如果您想更改星期的開始/結束日期(即星期一至星期日),則可以更改DATEADD函數中的-2以更改此項。

Example on SQL Fiddle

(基於[]各地的列名,我猜測這是SQL-Server中。)

+0

在這種情況下,我們可以像下面這樣將一週的兩週分組爲一週 銷售 2012年1月14日110 – rockwell 2013-05-08 21:21:16

+0

您只需要稍微調整DATEDIFF函數,請參見[this SQL Fiddle]上的'TwoWeekly'視圖( http://www.sqlfiddle.com/#!3/76eb4/1) – GarethD 2013-05-08 21:55:28

+0

非常感謝Lot @GarethD – rockwell 2013-05-09 14:48:57