[英]Mysql Count distinct IDs in Sum(if())
I have following tables.我有下表。
Case案子
ID ID | Name姓名 |
---|---|
1 1 | Anton安东 |
2 2 | Elfriede埃尔弗里德 |
3 3 | Osram欧司朗 |
Appointments约会
ID ID | Duration期间 | Case案子 |
---|---|---|
1 1 | 70 70 | 1 1 |
2 2 | 70 70 | 2 2 |
Fastdocu with out appointment没有预约的 Fastdocu
ID ID | Duration期间 | Case案子 |
---|---|---|
1 1 | 15 15 | 2 2 |
2 2 | 15 15 | 2 2 |
3 3 | 50 50 | 3 3 |
3 3 | 8 8 | 3 3 |
I need sum up all duration and all appointments and the cases that are not in Appointments.我需要总结所有持续时间和所有约会以及不在约会中的案例。
The result should be结果应该是
Duration 88持续时间 88
Appointments 3约会 3
Cases 1案例1
Following Statement I have written以下我写的声明
Select sum(duration), count(DISTINCT ID), SUM(IF(`Case` NOT IN (1,2),1,0)) From Fastdocu
Suddenly the result is结果一下子就出来了
Duration 88持续时间 88
Appointments 3约会 3
Cases 2案例2
I must sum only distinct ids at the cases count.我必须在案例计数中仅对不同的 id 求和。 But the distinct seems to be forbidden in the if.但是 if 中似乎禁止了 distinct 。 How can I count the cases right?我怎样才能正确计算案件?
Use COUNT()
with a CASE
expression instead of SUM()
:将COUNT()
与CASE
表达式一起使用,而不是SUM()
:
SELECT SUM(duration) total_duration,
COUNT(DISTINCT ID) distinct_ids,
COUNT(DISTINCT CASE WHEN `Case` NOT IN (1,2) THEN `Case` END) cases_not_in_Appointments
FROM Fastdocu
Since COUNT()
does not have an ELSE
branch it will not count Case
s that do not satisfy the condition Case NOT IN (1,2)
because in this case the result of the CASE
expression will be NULL
.由于COUNT()
没有ELSE
分支,它不会计算不满足条件Case
Case NOT IN (1,2)
的 Case ,因为在这种情况下CASE
表达式的结果将为NULL
。
If you want to count the distinct id
s and not the distinct Case
s change to:如果要计算不同的id
而不是不同的Case
更改为:
COUNT(DISTINCT CASE WHEN `Case` NOT IN (1,2) THEN ID END)
See the demo .请参阅演示。
Results:结果:
total_duration总持续时间 distinct_ids distinct_ids cases_not_in_Appointments case_not_in_Appointments 88 88 3 3 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.