SQL计算值在多列中出现的次数?

时间:2017-02-13 16:46:52

标签: sql sql-server-2008

下面是我们CRM中的一个表格的示例,它不是我选择存储这些数据的方式,而是通过by,那将是什么' nice'如何计算每个团队选择每个选项的次数?

在我进入一个错综复杂的案件陈述之前问这里:)

+----------+--------+---------+---------+---------+
| PersonID |  Team  | Option1 | Option2 | Option3 |
+----------+--------+---------+---------+---------+
|        1 | Blue   | A       | B       | C       |
|        2 | Blue   | B       | C       | D       |
|        3 | Blue   | D       | A       | E       |
|        4 | Red    | A       | B       | D       |
|        5 | Red    | B       | A       | C       |
|        6 | Yellow | A       | B       | C       |
|        7 | Yellow | A       | C       | D       |
+----------+--------+---------+---------+---------+

提前致谢

2 个答案:

答案 0 :(得分:2)

您可以使用CROSS APPLY和表值构造函数将3个选项列拆分为单个列,然后执行计数:

SELECT  t.Team, upvt.[Option], COUNT(*) AS Occurances
FROM    dbo.T
CROSS APPLY (VALUES (t.Option1), (t.Option2), (t.Option3)) AS upvt ([Option])
GROUP BY t.Team, upvt.[Option]
ORDER BY t.Team, upvt.[Option];

所以这会给:

Team       Option   Occurances
-------------------------------
Blue        A           2
Blue        B           2
Blue        C           2
Blue        D           2
Blue        E           1
Red         A           2
Red         B           2
Red         C           1
Red         D           1
Yellow      A           2
Yellow      B           1
Yellow      C           2
Yellow      D           1

答案 1 :(得分:0)

您可以使用UNION ALL将值移动到单个列中,然后执行聚合:

select 
    team, option, count(*) cnt
from(
    select team, option1 option from t union all
    select team, option2 from t union all
    select team, option3 from t 
)t group by team, option;