Return 范围内每个日期一列

Return a column per date in a range

我正在使用以下 SQL 查询:

select  brn,
        [time],
        sum(value) as [value]
from dbo.sales 
where date = '2014-12-31 00:00:00'     
    and brn = 1 
    and [time]!='ZZZZ'
group by brn, [time]
order by brn, [time]

我得到的结果是:

brn time    value
1   0800    0.00
1   0900    52.79
1   1000    5.73
1   1100    9.63
1   1200    200.08

现在我想要几个日期的结果(一年 - 从 31-12-201431-12-2015),

例如:

brn time    31/12/2014  01/01/2015  02/01/2015  03/01/2015
1   800     5.73        5.73        5.73        5.73
1   900     52.79       52.79       52.79       52.79
1   1000    5.73        5.73        5.73        5.73
1   1100    9.63        9.63        9.63        9.63
1   1200    200.08      200.08      200.08      200.08

对于为日期构建的列名,您可以创建 SQL dates table 然后使用动态 SQL,您可以将这些用作 select 字段 也许您可以检查 dynamic pivot sql query 如何将日期 table 的字段值连接到数据透视查询字段

这是SQL脚本

DECLARE @dates nvarchar(max)
SELECT @dates =
 STUFF(
 (
    SELECT ', value as [' + convert(varchar(30), cast([date] as date), 112) + ']'
    FROM [dbo].[DateTable]('20150101', '20151231')
    for xml path('')
 ),
 1,1,'')

DECLARE @SQL nvarchar(max)
SELECT @SQL = N'select brn, time, value, ' + @dates + ' from mydata'
exec sp_executesql @SQL 

输出如下

您可以格式化日期值的字符串表示形式,如您在 SQL Format Date 文章中所见。 代替参数 112,您可以使用 103 作为 dd/mm/yyyy 例如

希望对解决有帮助

您可以使用条件聚合:

select brn, [time],
       sum(case when date = '2014-12-31' then value else 0 end)) as value_20141231,
       sum(case when date = '2015-01-01' then value else 0 end)) as value_20150101,
       . . .
from dbo.sales 
where brn = 1  and 
     [time] <> 'ZZZZ'
group by brn, [time]
order by brn, [time];

您还可以使用 and date in ('2014-12-31', '2015-01-01', . . .).

限制 where 中的日期

您可以使用动态 SQL 旋转:

select  brn,
        [time],
        sum(value) as [value],
        [date]
INTO #temp
from dbo.sales 
where brn = 1 and [time]!='ZZZZ'
     AND [date] between '2014-12-31' and '2015-12-31'
group by brn, [time], [date]


DECLARE @sql nvarchar(max),
        @col nvarchar(max)

SELECT @col = (
    SELECT DISTINCT ','+QUOTENAME([date])
    FROM #temp
    FOR XML PATH ('')
)

SELECT @sql = N'
SELECT *
FROM #temp
PIVOT (
    MAX([value]) FOR [date] IN ('+STUFF(@col,1,1,'')+')
) as pvt)'

EXEC sp_executesql @sql