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

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

4

1 回答 1

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来改变它。

SQL Fiddle 示例

(根据[]周围的列名,我猜这是 SQL-Server。)

于 2013-04-11T08:31:04.247 回答