SQLite在1列中的值计数和按ID分组

问题描述 投票:1回答:2

我一直在努力得到我的表的值的计数,到目前为止它没有给我预期的输出。我已经尝试过Count和Group By的所有组合,但没有任何效果。

这是我桌子的片段

=========================
id | budget_id | type
=========================
1  | 1         | expenses
2  | 1         | expenses
3  | 1         | savings
4  | 1         | expenses
5  | 1         | expenses
6  | null      | savings
7  | 1         | savings
8  | 2         | expenses
9  | 2         | savings

所以我想要计算费用和节省的总数,并按budget_id进行分组

预期输出必须是这样的(必须忽略budget_id中的空值,因此budget_id = 1的节省为'2'):

=============================================
budget_id | savings         | expenses
=============================================
1         | 2               | 4
2         | 1               | 1

但输出是这样的:

=============================================
budget_id | savings         | expenses
=============================================
null      | 1               | 1
1         | 2               | 2
1         | 4               | 4
2         | 1               | 1
2         | 1               | 1

这是查询:

SELECT budget_id, count(CASE type WHEN 'savings' THEN 1 ELSE 0 END) savings, count(CASE type WHEN 'expenses' THEN 1 ELSE 0 END) expenses
from expenses_savings
group by budget_id, type

谢谢!

sqlite count
2个回答
0
投票

不要将type包含在group by中,因此对于相同的预算,您没有多个结果。

使用sum而不是count来计算不同的事件。

明确排除预算为空的行。

SELECT 
    budget_id, 
    sum(CASE type WHEN 'savings' THEN 1 ELSE 0 END) number_of_saved, 
    sum(CASE type WHEN 'expenses' THEN 1 ELSE 0 END) number_of_spent 
from expenses_savings 
where budget_id is not null
group by budget_id

0
投票

count更改为sum,并仅通过budget_id汇总:

SELECT
    budget_id,
    SUM(CASE WHEN type = 'savings'  THEN 1 ELSE 0 END) number_of_saved,
    SUM(CASE WHEN type = 'expenses' THEN 1 ELSE 0 END) number_of_spent
FROM expenses_savings
GROUP BY budget_id

除了使用错误的分组之外,使用COUNT的问题在于它实际上只计算零和一。如果你想使用COUNT,那么你可以尝试以下查询:

SELECT
    budget_id,
    COUNT(CASE WHEN type = 'savings'  THEN 1 END) number_of_saved,
    COUNT(CASE WHEN type = 'expenses' THEN 1 END) number_of_spent
FROM expenses_savings
GROUP BY budget_id

现在对于非匹配类型,计算的值将是NULL(这是ELSE表达式中的默认CASE值),因此将被计数忽略。

© www.soinside.com 2019 - 2024. All rights reserved.