计算多列中id的出现次数

时间:2014-11-17 06:33:43

标签: sql sql-server tsql count

好的,我在这里做错了什么。这应该很简单......

我有一张没有规范化的表格。我想得一下表中三列中出现的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'附近的语法不正确。"

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;