简体   繁体   English

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

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

i have a database where i am storing integers in columns in a way like this 我有一个数据库,我以这种方式将整数存储在列中
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 0 1 0 1 0 1 0
0 1 2 2 0 1 2 2

so i want to get count of each column where value is 1 for example. 因此,我想获取例如值为1的每一列的计数。
I ll be very thankful :) 我会非常感激的:)

I have tried using many queries but i don't know how to work in this way I have also checked stack over flow and many other websites too but somehow i am still stuck at this problem. 我尝试使用许多查询,但是我不知道如何使用这种方式,我也检查了流量和许多其他网站的堆栈,但是仍然以某种方式我仍然停留在此问题上。 I have tried using IN clause too. 我也尝试过使用IN子句。

I have tried using select statement by using OR and AND but i knew that this will not work and it gives improper results. 我已经尝试通过使用OR和AND来使用select语句,但是我知道这将不起作用,并且会给出不正确的结果。

It depends a bit on what you mean. 这取决于您的意思。 If you want to count the number of times the value 1 appears in your tables, you can use count(*) : 如果要计算值1在表格中出现的次数,可以使用count(*)

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

Or you could use case expressions: 或者,您可以使用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