0

我有三个表,比如 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 -- number 3 appeared only 3 times

同样,第二个最常见值的输出将是:

2 -- number 2 appeared 4 times

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

1 -- number 1 appeared 7 times
4

3 回答 3

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
于 2018-11-21T16:12:27.223 回答
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;
于 2018-11-21T16:05:03.480 回答
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

...它非常易读,并且不使用任何难以理解的概念。

于 2018-11-21T16:40:39.767 回答