一行中多个case语句的SQL结果

时间:2014-10-27 13:05:13

标签: sql case

我有一张包含以下内容的表:

EXTDEP EXTCODE PRICE
200     10001   200
500     10001   25
600     10001   36

我想要的结果:

EXTCODE PRICE200 PRICE500 PRICE600
10001    200       25         36

我得到的结果:

EXTCODE PRICE200 PRICE500 PRICE600
10001    NULL      NULL        36
10001    NULL       25        NULL
10001    200       NULL       NULL  

我的代码:

SELECT  
      [ExtCode]

      case when extdep = '200' then price1 end as '200', 
      case when extdep = '500' then price1 end AS '500', 
      case when extdep = '600' then price1 end AS '600'

有什么想法吗? :)

3 个答案:

答案 0 :(得分:5)

尝试将聚合应用于CASE语句:

SELECT  
      [ExtCode],

      MAX(case when extdep = '200' then price1 end) as '200', 
      MAX(case when extdep = '500' then price1 end) AS '500', 
      MAX(case when extdep = '600' then price1 end) AS '600'
FROM your_table
GROUP BY ExtCode

答案 1 :(得分:3)

您也可以像这样使用PIVOT功能:

SELECT [ExtCode],
     [1] AS '200',
     [2] AS'500',
     [3] AS'600'
FROM
 (
       Select [ExtCode], extdep, price1
       From your_table
  ) src
PIVOT
  ( 
      Max(price1)
      For extdep in ([1], [2], [3])
  ) piv 

答案 2 :(得分:2)

这是使用PIVOT

的替代方法
SELECT *
FROM [table]
    PIVOT (MAX(PRICE) FOR EXTDEP IN ([200], [500], [600])) T

这会生成以下输出

EXTCODE     200         500         600
----------- ----------- ----------- -----------
10001       200         25          36