我有一个表格,其中包含单位的详细信息 - 此表格的内容类似于以下内容:
| flat | description | Amount | Date
--------------------------------------
| flat1 | electricity | 1 |1/1/2016
| flat1 | water | 2 |1/1/2016
| flat1 | levy | 3 |1/1/2016
| flat2 | electricity | 1 |1/1/2016
| flat2 | water | 2 |1/1/2016
| flat2 | levy | 3 |1/1/2016
我需要一个可以产生如下内容的SQL视图,我们将不胜感激任何帮助:
| Flat | electricity | water|levy | next description| and so on |
---------------------------------------------------------------
| flat1 | 1 | 2 | 3 | next amount | next amount |
| flat2 | 1 | 2 | 3 | next amount | next amount |
答案 0 :(得分:1)
这称为表pivoting
。这是使用conditional aggregation
的一个选项,假设您知道潜在列的数量:
select flat,
max(case when description = 'electricity' then amount end) electricity,
max(case when description = 'water' then amount end) water,
max(case when description = 'levy' then amount end) levy
from yourtable
group by flat
如果您不知道最大列数,请查看dynamic pivot
- 有很多关于如何操作的示例:
答案 1 :(得分:0)
drop table #temp
create table #temp (flat varchar(5), description varchar(128), amount int, date datetime)
insert into #temp (flat, description, amount, date) values
('flat1','electricity',1,'1/1/2016'),
('flat1','water',2,'1/1/2016'),
('flat1','levy',3,'1/1/2016'),
('flat2','electricity',1,'1/1/2016'),
('flat2','water',2,'1/1/2016'),
('flat2','levy',3,'1/1/2016')
select * from #temp
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(description)
FROM #temp
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT flat, ' + @cols + ' from
(select flat,amount, description from #temp) x
pivot
(
max(amount)
for description in (' + @cols + ')
) p '
execute(@query)
您可以通过在@query部分中放置WHERE子句来添加日期过滤器。即来自#temp,其中日期介于< 1/1 / 2016'和' 3/1 2016'