ccampo
ccampo

Reputation: 1503

Removing duplicates and combining data from one table in a SQL query

I would like to create the following table (table 1):

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

from the following table (table 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
...

I am trying to create a select query to grab the relevant information from table 2 and create table 1 out of it. I will then turn this into a view.

I am essentially lost at this point. I tried doing the following:

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

This gives interesting results, but it is clearly not what I want. I understand this is the wrong query, and I should probably do this using joins, but when I went that route the query would not execute. I am having a brain fart here and help would be very much appreciated. Thanks!

Upvotes: 2

Views: 109

Answers (1)

Vikdor
Vikdor

Reputation: 24124

You are looking for this:

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'

Upvotes: 3

Related Questions