我在使用MySQL并且无法计算总数。我正在尝试找出一个SQL查询,它将使用以下数据和查询返回正确的结果。我想得到总案件的数量。在我的查询结果中,F和I计数是正确的M案例计数关闭。如果案件有一个F那么它应该算作F案件而不是我的查询正在进行的M案件。
数据:
BKNUM CG Charge Description Severity
123456 1 POSS CONT SUB W/I MAN/DEL/SELL F
123456 1 POSS LEGEND DRUG W/O PRESCRIPTION M
654321 1 VIOLATION OF PROBATION M I
987654 1 AGGRAVATED ASSAULT F
987654 1 POSS OF HANDGUN WHILE INTOXICATED M
987654 1 POSSESSION OF PROHIBITED WEAPON M
876543 1 VIOLATION OF PROBATION M I
765432 1 CRIM ATT-BURGLARY BUILDING F
765432 1 POSSESSION OF BURGLARY TOOLS M
234567 1 POSS MARIJUANA W/I MAN/DEL/SELL F
234567 1 DRIVING WHILE LICENSE S/R/C M
234567 1 IMPROPER DISPLAY OF REGISTRATION M
345678 1 DRIVING WHILE LICENSE S/R/C M
345678 1 EVADING ARREST M
345678 1 RESISTING OFFICIAL DETENTION M
345678 1 UNLAWFUL POSS WEAPON M
345678 1 POSS OF CONT SUBSTANCE M
345678 1 CRIM ATT-POSS OF CONT SUB-MARIJUANA M
查询:
Select Severity as 'Charge CLass',
Count(Distinct BKNUM, CG) as 'Total Cases',
Count(BKNUM) as 'Toatl Charges'
From test
group by severity
结果我得到:
Charge Class Total Cases Total Charges
F 4 4
I 2 2
M 5 12
结果应该是:
Charge Class Total Cases Total Charges
F 4 4
I 2 2
M 1 12
非常感谢任何帮助。
答案 0 :(得分:0)
您需要在BKNUM上使用GROUP BY,在CG列上使用DISTINCT。请参阅Distinct on multiple columns in MySQL以供参考 - 它应该引导您找到您正在寻找的解决方案。
答案 1 :(得分:0)
SELECT CASE WHEN S = 1 THEN 'I' WHEN S = 2 THEN 'M' ELSE 'F' END
, Qty
, BKNUM
, CG
FROM (
SELECT MAX(CASE WHEN Severity = 'I' THEN 1 WHEN Severity = 'M' THEN 2 ELSE 3 END) AS S
, COUNT(*) AS Qty
, BKNUM
, CG
FROM Test
GROUP BY BKNUM, CG ) AS t
答案 2 :(得分:0)
不是最漂亮的查询,但我认为它应该有效:
select t.severity, count(distinct bknum) "Total Cases", a.c "Total Charges"
from test t
join (select severity, count(*) c from test group by severity) a on t.severity = a.severity
where t.severity in ('i','f')
or (t.severity = 'm' and bknum not in (select bknum from test where severity = 'f'))
group by t.severity, a.c
或许这个:
select t.severity, count(distinct bknum, cg) "Total Cases", a.c "Total Charges"
from test t
join (select severity, count(*) c from test group by severity) a on t.severity = a.severity
where t.severity in ('i','f')
or (t.severity = 'm' and (bknum, cg) not in (select bknum, cg from test where severity = 'f'))
group by t.severity, a.c