删除重复项并在SQL查询中组合来自一个表的数据

时间:2012-09-11 16:09:30

标签: sql sql-server database

我想创建下表(表1):

CHANNEL    START    STOP    SIGNAL    NOISE
-------------------------------------------
chan1      0        1       A         B
chan2      10       20      C         D
...

从下表(表2):

CHANNEL    START    STOP    TYPE      VALUE
-------------------------------------------
chan1      0        1       signal    A
chan1      0        1       noise     B
chan2      10       20      signal    C
chan2      10       20      noise     D
...

我正在尝试创建一个select查询来从表2中获取相关信息并从中创建表1。然后我会把它变成一个视图。

此时我基本上迷失了方向。我尝试了以下操作:

select distinct 
    table2.CHANNEL as CHANNEL_ID
    , table2.START as START_FREQ
    , table2.STOP_FREQ as STOP_FREQ
    , SIGNAL = CASE
      WHEN table2.TYPE = 'signal' THEN table2.VALUE
      END
    , NOISE_OFFSET = CASE
      WHEN table2.TYPE = 'noise' THEN table2.VALUE
      END

from 
    table2

这给出了有趣的结果,但显然不是我想要的。我知道这是错误的查询,我应该使用连接来做这个,但是当我走这条路线时,查询将不会执行。我在这里有一个大脑放屁,非常感谢帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

您正在寻找:

SELECT
      A.CHANNEL AS CHANNEL_ID,
      A.START AS START,
      A.STOP AS STOP,
      A.VALUE AS SIGNAL,
      B.VALUE AS NOISE
FROM
      table2 as A
      JOIN table2 as B
      ON 
          A.CHANNEL = B.CHANNEL AND 
          A.START = B.START AND 
          A.STOP = B.STOP AND
          A.TYPE = 'signal' AND
          B.TYPE = 'noise'