如何找到SQL中3列的众数?
How to find the mode of 3 columns in SQL?
在 SQL 中,我有一个包含 3 列的 table:
Month1
Month2
Month3
0
1
0
1
1
1
0
1
1
...等等。
我需要另一列,其中给出了 Month1
、Month2
和 Month3
的模式。
我的预期输出是:
Month1
Month2
Month3
Mode
0
1
0
0
1
1
1
1
0
1
1
1
到目前为止,我只计算了单个列的众数。不知道我们如何通过合并 3 列来水平地完成它。
您可以使用 CASE
表达式:
SELECT *, CASE WHEN Month1 + Month2 + Month3 <= 1 THEN 0 ELSE 1 END AS mode
FROM yourTable;
这应该有效,可以轻松扩展为 n 列:
select month1, month2, month3, ca.val
from t
cross apply (
select top 1 val
from (values
(month1),
(month2),
(month3)
) as v(val)
group by val
order by count(*) desc
) as ca
对于 SQL 服务器之外的 RDBMS,将 values(...)
替换为适当的 table 值构造函数,将 cross apply
替换为 [=22= 中的横向 join/sub 查询] 和 top 1
与 limit/offset...获取。
在 SQL 中,我有一个包含 3 列的 table:
Month1 | Month2 | Month3 |
---|---|---|
0 | 1 | 0 |
1 | 1 | 1 |
0 | 1 | 1 |
...等等。
我需要另一列,其中给出了 Month1
、Month2
和 Month3
的模式。
我的预期输出是:
Month1 | Month2 | Month3 | Mode |
---|---|---|---|
0 | 1 | 0 | 0 |
1 | 1 | 1 | 1 |
0 | 1 | 1 | 1 |
到目前为止,我只计算了单个列的众数。不知道我们如何通过合并 3 列来水平地完成它。
您可以使用 CASE
表达式:
SELECT *, CASE WHEN Month1 + Month2 + Month3 <= 1 THEN 0 ELSE 1 END AS mode
FROM yourTable;
这应该有效,可以轻松扩展为 n 列:
select month1, month2, month3, ca.val
from t
cross apply (
select top 1 val
from (values
(month1),
(month2),
(month3)
) as v(val)
group by val
order by count(*) desc
) as ca
对于 SQL 服务器之外的 RDBMS,将 values(...)
替换为适当的 table 值构造函数,将 cross apply
替换为 [=22= 中的横向 join/sub 查询] 和 top 1
与 limit/offset...获取。