2014-11-17 81 views
-1

好的,我在這裏做錯了什麼。這應該是簡單的...計算多列中id的發生率

我有一個表未規範化。我想要計算出現在表格的三列中的ID。

1 100 200 300 
2 200 700 800 
3 200 300 400 
4 100 200 300 

結果:

2 100 
4 200 
3 300 
1 400 
1 700 
1 800 

這裏是我的嘗試。工會工作。這是我的總結和分組嘗試失敗:

select sum(cnt), ICDCodeID from 
(
    select count(*) cnt, ICDCodeID1 ICDCodeID from encounter 
    where (ICDCodeID1 is not null) group by ICDCodeID1 
    UNION ALL 
    select count(*) cnt, ICDCodeID2 ICDCodeID from encounter 
    where (ICDCodeID2 is not null) group by ICDCodeID2 
    UNION ALL 
    select count(*) cnt, ICDCodeID3 ICDCodeID from encounter 
    where (ICDCodeID3 is not null) group by ICDCodeID3 
) group by cnt, ICDCodeID 

或更好的方式?

以下是我收到的錯誤:「關鍵字'GROUP'附近的語法錯誤。」

+0

這對此類問題的解決方案食譜。你做得很好。 – Mureinik

+0

Mureinik,但我的錯誤在哪裏? – ginalster

+0

什麼錯誤?您的帖子陳述此作品... – Mureinik

回答

0

也許這會有所幫助:

SELECT D.ICDCode, 
     COUNT(*) as Cnt 
    FROM(SELECT ICDCodeID1 AS ICDCode 
     FROM encounter 
     UNION 
      ALL 
     SELECT ICDCodeID2 AS ICDCode 
     FROM encounter 
     UNION 
      ALL 
     SELECT ICDCodeID3 AS ICDCode 
     FROM encounter 
    )D 
GROUP 
    BY D.ICDCode; 
+0

同樣的錯誤,我得到「不正確的語法靠近關鍵字」組「。」 – ginalster

+2

@ginalster現在你可以嘗試錯誤可能是由於缺少別名 –

+0

謝謝@Ganesh_Devlekar,它現在的作品,請參閱http://sqlfiddle.com/#!3/89bfd/2 – DirkNM

0

試試這個:

-- build sample data 
create table temp(
    id int, 
    col1 int, 
    col2 int, 
    col3 int 
) 
insert into temp 
select 1, 100, 200, 300 union all 
select 2, 200, 700, 800 union all 
select 3, 200, 300, 400 union all 
select 4, 100, 200, 300 

-- start 
;with cte(id, col_value) as(
    select id, col1 from temp union all 
    select id, col2 from temp union all 
    select id, col3 from temp 
) 
select 
    col_value, 
    count(*) 
from cte 
group by col_value 
-- end 

-- clean sample data 
drop table temp 
+0

我寧願單個sql語句,但如果不能完成,我會嘗試這一點。 Thx – ginalster

+0

好的。讓我知道這個是否奏效。 –