SQL有条件地调整数据

时间:2012-09-24 16:42:10

标签: sql pivot

我有以下难题要解决(确切的紧急业务分配) SQL SERVER 2008

我有一张这种表格的表格

ID    Market      SubMarket     Value
1       1          1              3
2       1          2              6
3       1          3              2
4       2          23             1
5       2          24             9

我有特定的MarketIDs,每个MarketID都有特定的SubMarketIDs(最多5个 - 我知道每个都可以) 例如,MarketID 1具有SubMarketID 1,2,3    MarketID 2有SubMarketIDs 23,24等 每个SubMarketID都有一个变量值

我必须在这种类型的固定表中转换我的数据

MarketID  SubMarketAvalue   SubMarketBValue   SubMarketCValue....SubMarketEValue

   1              3                 6                2                  null

   2              1                 9               null                null

SubMarketAValue必须包含较小的SubMarketID

的值

SubMarketBValue必须包含下一个更大的SubMarketID

的值

1 个答案:

答案 0 :(得分:2)

您没有指定RDBMS,但您可以在SQL Server 2005 +,Oracle和PostgreSQL中使用以下内容:

select market,
  max(case when rn = 1 then value end) as SubMarketAvalue,
  max(case when rn = 2 then value end) as SubMarketBvalue,
  max(case when rn = 3 then value end) as SubMarketCvalue,
  max(case when rn = 4 then value end) as SubMarketDvalue,
  max(case when rn = 5 then value end) as SubMarketEvalue
from 
(
  select id, market, submarket, value,
    row_number() over(partition by market 
                      order by market, submarket) rn
  from yourtable
) x
group by market

请参阅SQL Fiddle with Demo

相关问题