根据3个表中值出现的次数选择第n个顶行

时间:2018-11-21 15:57:08

标签: sql sql-server sql-rank

我有三个表,分别是A,B和C。每个表都有不同名称的列,例如D1,D2和D3。在这些列中,我的值介于1到26之间。如何计算这些值的出现并按该计数对它们进行排序? 示例:

TableA.D1
1
2
1
1
3

TableB.D2
2
1
1
1
2
3

TableC.D3
2
1
3

第3个最常用值的输出如下所示:

3 -- number 3 appeared only 3 times

同样,第二个最常用值的输出为:

2 -- number 2 appeared 4 times

并输出第一个最常用的值:

1 -- number 1 appeared 7 times

3 个答案:

答案 0 :(得分:0)

您可能想要:

select top (3) d1
from ((select d1 from tablea ta) union all
      (select d2 from tableb tb) union all
      (select d3 from tablec tc)
     ) t
group by d1
order by count(*) desc;

答案 1 :(得分:0)

SELECT DQ3.X, DQ3.CNT
(
    SELECT DQ2.*, dense_rank() OVER (ORDER BY DQ2.CNT DESC) AS RN
        (SELECT DS.X,COUNT(DS.X) CNT FROM
                (select D1 as X FROM TableA UNION ALL SELECT D2 AS X FROM TABLE2 UNION ALL SELECT D3 AS X FROM TABLE3) AS DS
            GROUP BY DS.X
        ) DQ2
) DQ3 WHERE DQ3.RN = 3   --the third in the order of commonness - note that 'ties' can be handled differently

答案 2 :(得分:0)

关于SQL脚本的一件事:它们很难非常容易地阅读。我非常热衷于使内容尽可能地具有可读性。所以我建议像这样:

declare @topThree TABLE(entry int, cnt int)
select TOP 3 entry,count(*) as cnt
    from
    (
        select d1 as entry from tablea UNION ALL
        select d2 as entry from tableb UNION ALL
        select d3 as entry from tablec UNION ALL
    ) as allTablesCombinedSubquery
    order by count(*)
select TOP 1 entry
    from @topThree
    order by cnt desc

...它的可读性极强,并且不使用任何难以理解的概念。