0

我有以下难题要解决(确切地说是一项紧急业务任务)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

我有特定的 MarketID,每个 MarketID 都有特定的 SubMarketID(最多 5 个 - 我知道每个可能如何)例如 MarketID 1 有 SubMarketIDs 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 的值

4

1 回答 1

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

于 2012-09-24T16:59:49.763 回答