在加入两张表前加总

时间:2013-04-11 07:46:50

标签: sql join

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

对此的任何帮助将不胜感激。提前谢谢

1 个答案:

答案 0 :(得分:1)

我强烈建议不要将其存储在一个表格中,如果您的每日数据发生任何变化,您的每周数据将需要更改为或者它将是错误的,而是创建一个视图,如下所示:

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

您可以按照您想要创建的表格的方式使用此方法,但这将始终与每日数据同步。如果您想更改周开始/结束日(即星期一 - 星期日),您可以更改-2函数中的DATEADD来更改此内容。

<强> Example on SQL Fiddle

(基于[]列名称,我猜这是SQL-Server。)