[英]How can I count the number of a value in a particular row using SQL?
數據庫
id decline maintaining losing
1 true false true
2 false false false
3 true true false
我想使用SQL語句基於id計算真實值的數量。
如果這是所有列,則使用此列:
SELECT id,
(case when decline = 'true' then 1 else 0 end) +
(case when maintaining= 'true' then 1 else 0 end) +
(case when losing= 'true' then 1 else 0 end) as HowMuchTrue
FROM YourTable
select sum(if(maintaining = 'true', 1, 0)) from table -- and here some conditions.
這個問題似乎有點模糊,但我想我知道你要干什么。 對於每一行,您要計算“ true”在其中顯示的次數。
為此,我們將使用CASE語句將true處理為1,將false處理為0。
SELECT
id,
CASE
WHEN decline = 'true' THEN 1
WHEN decline = 'false' THEN 0
else 'check your logic'
END as decline_processed,
CASE
WHEN maintaining = 'true' THEN 1
WHEN maintaining = 'false' THEN 0
else 'check your logic'
END as maintaining_processed,
CASE
WHEN losing = 'true' THEN 1
WHEN losing = 'false' THEN 0
else 'check your logic'
END as losing_processed
FROM
[table]
這為我們提供了以下結果:
id, decline_processed, maintaining_processed, losing_processed
1 , 1, 0, 1
2, 0, 0, 0
3, 1, 1, 0
從這里,我們可以獲取結果並收集它們,並獲得每一行的總和。
SELECT
id,
SUM(query_result_alias.decline_processed
+ query_result_alias.maintaining_processed
+ query_result_alias.losing_processed
) as number_of_true_values
FROM
[query with case statement above] as query_result_alias
GROUP BY
query_result_alias.id
這將得到以下結果,我相信可以回答您的問題:
id, number_of_true_values
1, 2
2, 0
3, 2
獎勵,我們可以將結果處理為摘要數據
SELECT
COUNT(query_result_alias2.id) as counter,
query_result_alias2.number_of_true_values
FROM
[query with case statement above] as query_result_alias2
GROUP BY
query_result_alias2.number_of_true_values
這樣可以得到具有每個真值數量的行數:
counter, number_of_true_values
2, 2
1, 0
使用樣本數據,您將只有兩個結果,但是較大的數據集將提供所有選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.