我有一张这样的表:
Item Name Name_location Price
1 item1_london london 10
1 item1_beijing bejing 10
2 item2_london london 20
2 item2_beijing bejing 20
基本上,这个表意味着我有很多项目each item will have a different name in different location (two locations: london and beijing)
。
如何查询以便我可以像这样获取表格:
Item london bejing Price
1 item1_london item1_beijing 10
2 item2_london item2_beijing 20
我正在使用MS SQL Server。
编辑:更新了两个表,添加了另一列
答案 0 :(得分:4)
如果您只有两个位置,那么您可以使用带有聚合的CASE
语句:
CASE with Aggregate :
select item,
max(case when Name_location = 'london' then name end) london,
max(case when Name_location = 'bejing' then name end) bejing,
sum(price) price
from yourtable
group by item
或
select item,
max(case when Name_location = 'london' then name end) london,
max(case when Name_location = 'bejing' then name end) bejing,
price
from yourtable
group by item, price
使用PIVOT
函数,有两种静态/动态方式:
静态PIVOT
select item, [london], [bejing], price
from
(
select item, name, name_location, price
from yourtable
) x
pivot
(
max(name)
for name_location in ([london], [bejing])
) p
如果你有一个已知数量的值,静态PIVOT
版本会很好用,如果你有一个未知的数字,那么你可以使用动态的sql:
动态数据透视:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name_location)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT item,' + @cols + ', price from
(
select item, name, name_location, price
from yourtable
) x
pivot
(
max(name)
for name_location in (' + @cols + ')
) p '
execute(@query)
答案 1 :(得分:1)
使用pivot
select *
from YourTable src
pivot (max(name) for name_location in ([london], [beijing]) ) p
答案 2 :(得分:0)
SELECT DISTINCT o.Item, l.itemName as London, b.ItemName as Beijing
FROM myTable o inner join myTable l ON o.item = l.item
INNER JOIN myTable b ON o.item = b.item
WHERE l.location = 'london' AND b.location = 'beijing'
SQLFiddle链接:http://sqlfiddle.com/#!3/93c2a/8
答案 3 :(得分:0)
select item,london,beijing
from t1
pivot(max(Name) for Name_location in (london, beijing)) pvt
select item,london,beijing,price
from t1
pivot(max(Name) for Name_location in (london, beijing)) pvt