选择中的多个案例的单行

时间:2014-09-24 09:54:47

标签: sql sql-server

我需要一个下面的Senario解决方案

我有一个带有列的表temp:a, b, c, d,数据如下所示:

TABLE TEMP

+---+----+----+----+
|a  |  b |  c |  d |
+===+====+====+====+
| 1 | 1  | 1  |  m |
| 1 | 2  | 1  |  d |
| 1 | 3  | 1  |  w |
| 2 | 1  | 1  |  m |
| 2 | 2  | 1  |  d |
| 2 | 2  | 1  |  w |
+---+----+----+----+ 

QUERY

SELECT CASE WHEN B=1 AND C=1 THEN D END as T1,
CASE WHEN B=2 AND C=1 THEN D END as T2,
CASE WHEN B=3 AND C=1 THEN D END as T3
FROM TEMP
WHERE A=1

上面的查询为多行提供了空值,其中值不存在

我需要一个带有单行的结果集,如下所示:

预期结果

+------+-------+------+
| T1   |   T2  |  T3  |
+======+=======+======+
| m    |   d   |  w   |
+------+-------+------+

1 个答案:

答案 0 :(得分:0)

这样做(使用CTE)

QUERY

    WITH 
    CTE1 as (select top 1 d as T1 from temp where b=1 and c=1),
    CTE2 as (select top 1 d as T2 from temp where b=2 and c=1),
    CTE3 as (select top 1 d as T3 from temp where b=3 and c=1)

    select CTE1.*, CTE2.*, CTE3.*
    FROM CTE1 CROSS JOIN CTE2 CROSS JOIN CTE3

SQL fiddle

About the multiple CTE

请告诉我它是否有效!