返回范围中每个日期的列

时间:2016-10-05 10:50:24

标签: sql sql-server tsql pivot

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

3 个答案:

答案 0 :(得分:2)

您可以使用带有数据透视的动态S​​QL:

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

答案 1 :(得分:0)

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

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

输出如下

enter image description here

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

我希望它有助于解决方案

答案 2 :(得分:0)

您可以使用条件聚合:

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

您还可以使用where来限制and date in ('2014-12-31', '2015-01-01', . . .)中的日期。