我有一个PIVOT情况。
源表列:
Title Description Datetime RecordsCount
A California 2015-07-08 10:44:39.040 5
A California 2015-07-08 12:44:39.040 6
A California 2015-05-08 15:44:39.040 3
B Florida 2015-07-08 16:44:39.040 2
B Florida 2015-05-08 19:44:39.040 4
现在我需要将其转换为
2015-07-08 2015-05-08
Title Description
A California 11 3
B Florida 2 4
如果我们在相同的日期(无论时间)有两个记录计数,那么将它们相加,否则显示在不同的列中。
尝试写这样的东西,但它会引发错误。
Select * from #DataQualTest
PIVOT (SUM(RecordCount) FOR DateTime IN (Select Datetime from #DataQualTest) )
AS Pivot_Table
请帮我解决这个问题。
由于
答案 0 :(得分:1)
不完全是单词解决方案,但这应该给你一个方向。
create table #tmp
(
country varchar(max)
, date1 datetime
, record int
)
insert into #tmp values ('California', '2010-01-01', 2)
insert into #tmp values ('California', '2010-01-01', 5)
insert into #tmp values ('California', '2012-01-01', 1)
insert into #tmp values ('Florida', '2010-01-01', 3)
insert into #tmp values ('Florida', '2010-01-01', 5)
select * from #tmp
pivot (sum(record) for date1 in ([2010-01-01], [2012-01-01])) as avg
输出
country 2010-01-01 2012-01-01
California 7 1
Florida 8 NULL
答案 1 :(得分:0)
如果您想要更灵活,则需要进行一些预处理才能从完整时间戳到天(以便稍后在PIVOT
的分组中实际获得预期效果):
CREATE VIEW DataQualTestView AS
SELECT
title
, description
, DATEFROMPARTS (DATEPART(yyyy, date_time),
DATEPART(mm, date_time),
DATEPART(dd, date_time)) AS day_from_date_time
, recordsCount
FROM DataQualTest
;
从那里你可以继续:
DECLARE @query AS NVARCHAR(MAX)
DECLARE @columns AS NVARCHAR(MAX)
SELECT @columns = ISNULL(@columns + ',' , '')
+ QUOTENAME(day_from_date_time)
FROM (SELECT DISTINCT
day_from_date_time
FROM DataQualTestView) AS TheDays
SET @query =
N'SELECT
title
, description
, ' + @columns + '
FROM DataQualTestView
PIVOT(SUM(recordsCount)
FOR day_from_date_time IN (' + @columns + ')) AS Pivoted'
EXEC SP_EXECUTESQL @query
GO
......并且会得到:
| title | description | 2015-05-08 | 2015-07-08 |
|-------|-------------|------------|------------|
| A | California | 3 | 11 |
| B | Florida | 4 | 2 |
查看实际操作:SQL Fiddle。
如果需要调整/进一步详细说明,请发表评论。