从同一个表中加入两个选择查询

时间:2013-02-01 14:24:13

标签: sql sql-server select join

该表包含ID列,valueHeading列和值列。我想将value列分成两个名为valueHeading1和valueHeading2的新列,具体取决于valueHeading值的类型。

所以我想加入这个选择: 修改:完全加入

SELECT ID
      ,valueHeading
      ,value as 'valueHeading1'
FROM table1
WHERE valueHeading = 'valueHeading1'

使用此选择:

SELECT ID
      ,value as 'valueHeading2'
FROM table1
WHERE valueHeading = 'valueHeading2'

各自的ID。我该怎么做?

编辑以说明我想要做的事情:

原始表:

ID    valueHeading    value
0     valueHeading1    a
0     valueHeading2    a
1     valueHeading1    ab
1     valueHeading2    NULL
2     valueHeading1    abcd
2     valueHeading2    abc

新表:

ID    valueHeading1    valueHeading2
0          a               a
1          ab              NULL
2         abcd             abc

4 个答案:

答案 0 :(得分:5)

尝试类似:

SELECT ID
      , CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END AS valueHeading1
      , CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END AS valueHeading2
FROM table1
WHERE valueHeading IN ('valueHeading1', 'valueHeading2')

如果要为每个ID重新组合一行的所有值,可以尝试:

SELECT ID
      , MAX(CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END) AS valueHeading1
      , MAX(CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END) AS valueHeading2
FROM table1
WHERE valueHeading IN ('valueHeading1', 'valueHeading2')
GROUP BY ID
HAVING MAX(CASE WHEN valueHeading = 'valueHeading1' THEN value ELSE NULL END) IS NOT NULL
OR MAX(CASE WHEN valueHeading = 'valueHeading2' THEN value ELSE NULL END) IS NOT NULL

SQLFiddle。我也尝试过Oracle 11g和MSSQL 2012,每次都有效。

答案 1 :(得分:5)

如果您只需要加入,请使用此功能。如果你不需要加入,请使用优雅的方式。

SELECT * FROM 
    (SELECT ID
          ,valueHeading
          ,value as 'valueHeading1'
    FROM table1
    WHERE valueHeading = 'valueHeading1') AS TAB_1, 
    (SELECT ID
          ,value as 'valueHeading2'
    FROM table1
    WHERE valueHeading = 'valueHeading2') AS TAB_2
    WHERE TAB_1.ID = TAB_2.ID

答案 2 :(得分:3)

在SQLServer2005中+可能使用PIVOT

SELECT ID, valueHeading1, valueHeading2
FROM
(
 SELECT *
 FROM dbo.test28
 WHERE valueHeading IN ('valueHeading1', 'valueHeading2')
 ) x
 PIVOT
 (
  MAX(value)
  FOR valueHeading IN ([valueHeading1], [valueHeading2])
  ) p

SQLFiddle上的演示

答案 3 :(得分:0)

自我加入可能是一个简单的解决方案

SELECT DISTINCT t1.ID, t1.value as valueHeading1, t2.value as valueHeading2, 
FROM table1 t1
INNER JOIN table1 t2 ON t1.ID = t2.ID
WHERE t1.valueHeading <> t2.valueHeading