繁体   English   中英

选择查询多个具有相同类型值的列

[英]select query for multiple columns with same type of values

我有一个数据库,我以这种方式将整数存储在列中
1 1 1 1
1 1 1 1
1 0 1 0
0 1 2 2

因此,我想获取例如值为1的每一列的计数。
我会非常感激的:)

我尝试使用许多查询,但是我不知道如何使用这种方式,我也检查了流量和许多其他网站的堆栈,但是仍然以某种方式我仍然停留在此问题上。 我也尝试过使用IN子句。

我已经尝试通过使用OR和AND来使用select语句,但是我知道这将不起作用,并且会给出不正确的结果。

这取决于您的意思。 如果要计算值1在表格中出现的次数,可以使用count(*)

select
(select count(*) from myTable where col1 = 1) +
(select count(*) from myTable where col2 = 1) +
(select count(*) from myTable where col3 = 1) +
[...]

或者,您可以使用case表达式:

select sum(*) from (
    select
    (case when col1 = 1 then 1 else 0 end) +
    (case when col2 = 1 then 1 else 0 end) +
    (case when col3 = 1 then 1 else 0 end)
    from myTable
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM