SQL Server - 如何计算多列中不同条目的数量?

时间:2015-02-16 17:59:02

标签: sql-server sql-server-2008

我有一张类似的表:

FORM_NUM         DOB_1           DOB_2            DOB_3
1                06Jul1973                        20Jan1994
1                06Jul1973       12Mar1980        20Jan1994
2                17Oct1960       12Dec1996        12Dec1996
2                18Feb2000
2                17Oct1960       17Oct1960

我想计算每个表单有多少个不同的生日。您可以将每行视为表单的子集。在此示例中,表单1有3个不同的生日,表单2有3个不同的生日。

我知道用于计算每列不同条目数的代码 COUNT(DISTINCT ...),但有时相同的生日位于多列中,因此简单地将每列的不同计数相加不起作用。

我希望输出看起来像:

FORM_NUM      COUNT
1             3
2             3

实现这一目标的最佳方法是什么?

编辑:它有效。代码就是这样......



SELECT FORM_NUM, COUNT(DOB) FROM  

(SELECT FORM_NUM, DOB_1 as DOB FROM table WHERE LEN(DOB_1) > 0
UNION
SELECT FORM_NUM, DOB_2 as DOB FROM table  WHERE LEN(DOB_2) > 0
UNION
SELECT FORM_NUM, DOB_3 as DOB FROM table WHERE LEN(DOB_3) > 0
UNION
SELECT FORM_NUM, DOB_4 as DOB FROM table WHERE LEN(DOB_4) > 0
UNION
SELECT FORM_NUM, DOB_5 as DOB FROM table WHERE LEN(DOB_5) > 0)TMP


GROUP BY FORM_NUM




2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

select FORM_NUM, count(DOB) from (
   select FORM_NUM, DOB_1 as DOB from table where DOB_1 is not null
   union
   select FORM_NUM, DOB_2 as DOB from table where DOB_2 is not null
   union
   select FORM_NUM, DOB_3 as DOB from table where DOB_3 is not null
) TMP
GROUP BY FORM_NUM

这将分别选择每个字段,union将删除重复值

答案 1 :(得分:2)

SELECT FORM_NUM, COUNT(DOB) COUNT FROM

(SELECT FORM_NUM, DOB_1 DOB FROM YOURTABLE
UNION
SELECT FORM_NUM, DOB_2 DOB FROM YOURTABLE
UNION
SELECT FORM_NUM, DOB_3 DOB  FROM YOURTABLE) A GROUP BY FORM_NUM