0

我有一张这样的桌子:

   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。

编辑:更新了两个表,添加了另一列

4

4 回答 4

4

如果您只有两个位置,则可以使用CASE带有聚合的语句:

聚合案例

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

请参阅带有演示的 SQL Fiddle

或者

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功能,有两种方式,静态/动态:

静态枢轴

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

请参阅带有演示的 SQL Fiddle

如果你有一个已知数量的值,静态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)

请参阅带有演示的 SQL Fiddle

于 2012-10-26T10:07:27.807 回答
1

用一个pivot

select * 
from YourTable src
pivot (max(name) for name_location in ([london], [beijing]) ) p
于 2012-10-26T09:54:23.777 回答
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
于 2012-10-26T10:02:30.177 回答
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

于 2012-10-26T09:55:27.663 回答