SQL 服务器 - 查找水平出现

SQL Server - find horizontal occurrences

我正在使用 SQL Server 2008R2 并且 tableA 有四列 res_id,res_id2, res_id3,res_id4 数值。 我想找出每一行(met 列)中相同 ID 的出现次数,不包括 0 或 null

示例:

golf_id res_id  res_id2 res_id3 res_id4     met     
1579    2068252 2068252 NULL    0           1
1492    2076015 2076015 2076016 2076016     2
1494    2076046 2076046 2076046 2076047     2
1617    2077041 2077042 2077043 2077044     4
1545    2076102 2076102 NULL    NULL        1

谢谢

一个简单的解决方案是逆透视您的数据,然后 COUNT DISTINCT 值。我很确定这会在 2008 R2 上运行(尽管我无法访问这样的实例,也没有在十年的大部分时间里访问过这样的实例)。

WITH YourTable AS(
    SELECT *
    FROM (VALUES(1579,2068252,2068252,NULL   ,0      ),
                (1492,2076015,2076015,2076016,2076016),
                (1494,2076046,2076046,2076046,2076047),
                (1617,2077041,2077042,2077043,2077044),
                (1545,2076102,2076102,NULL   ,NULL   ))V(golf_id,res_id,res_id2,res_id3,res_id4))
SELECT YT.golf_id,
       YT.res_id,
       YT.res_id2,
       YT.res_id3,
       YT.res_id4,
       (SELECT COUNT(DISTINCT NULLIF(V.res_id,0))
        FROM (VALUES(res_id),(res_id2),(res_id3),(res_id4))V(res_id)) met
FROM YourTable YT;

一般的做法是这样的:

select 
    a.golf_id
,   a.res_id
,   a.res_id2
,   a.res_id3
,   a.res_id4
,   b.met
from (
    select b.golf_id, count(distinct res_id) as met
    from (
        select golf_id, res_id from tableA where res_id > 0
        union all
        select golf_id, res_id2 from tableA where res_id2 > 0
        union all
        select golf_id, res_id3 from tableA where res_id3 > 0
        union all
        select golf_id, res_id4 from tableA where res_id4 > 0
        ) as b
    group by b.golf_id
    ) as b
join tableA as a
    on a.golf_id = b.golf_id