SQL Server:每行中最常见的值

时间:2017-01-20 10:02:52

标签: sql sql-server database tsql

如何在SQL Server的每一行中找到最常用的值?

示例:

1 a d a a c a b  -->    a
2 b a c b b b d  -->    b
3 h a h h b c d  -->    h    
4 d d c h g p m  -->    d
5 e e g h d e h  -->    e

在第一行中,' a'是最常见的价值等。

1 个答案:

答案 0 :(得分:2)

考虑到这些值位于不同的列中,使用UNPIVOT查询,解决方案看起来就像......

测试数据

Declare @T table (ID INT , Col1 varchar(1) , Col2 varchar(1) , Col3 varchar(1)
             , Col4 varchar(1) , Col5 varchar(1) , Col6 varchar(1) , Col7 varchar(1))
Insert Into @T values
('1','a','d','a','a','c','a','b'),
('2','b','a','c','b','b','b','d'),
('3','h','a','h','h','b','c','d'),
('4','d','d','c','h','g','p','m'),
('5','e','e','g','h','d','e','h');

<强>查询

WITH X AS (
Select ID , Val,  COUNT(*)total
       ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY COUNT(*) DESC) rn
from @T 
 UNPIVOT (Val FOR N IN (Col1,Col2,Col3,Col4,Col5,Col6,Col7))up
GROUP BY ID , Val 
)
Select t.* ,  Val 
FROM X 
INNER JOIN @T t ON x.ID = t.ID 
WHERE rn = 1

结果集

+----+------+------+------+------+------+------+------+-----+
| ID | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 | Col7 | Val |
+----+------+------+------+------+------+------+------+-----+
|  1 | a    | d    | a    | a    | c    | a    | b    | a   |
|  2 | b    | a    | c    | b    | b    | b    | d    | b   |
|  3 | h    | a    | h    | h    | b    | c    | d    | h   |
|  4 | d    | d    | c    | h    | g    | p    | m    | d   |
|  5 | e    | e    | g    | h    | d    | e    | h    | e   |
+----+------+------+------+------+------+------+------+-----+