我陷入两难境地,我希望有人能够帮助我。我试图从我的旧教科书中解决一些问题,这不是书中的问题,但数据是,我只是想看看我是否还可以在SQL中工作,所以这里是。执行此代码时,
SELECT COUNT(code_description) "Number of Different Crimes", last, first,
code_description
FROM
(
SELECT criminal_id, last, first, crime_code, code_description
FROM criminals
JOIN crimes USING (criminal_id)
JOIN crime_charges USING (crime_id)
JOIN crime_codes USING (crime_code)
ORDER BY criminal_id
)
WHERE criminal_id = 1020
GROUP BY last, first, code_description;
我得到了这些结果:
Number of Different Crimes LAST FIRST CODE_DESCRIPTION
1 Phelps Sam Agg Assault
1 Phelps Sam Drug Offense
不可避免地,我希望每一行的不同罪行数量为2,因为这名罪犯有两项独特的罪行。我希望它显示如下:
Number of Different Crimes LAST FIRST CODE_DESCRIPTION
2 Phelps Sam Agg Assault
2 Phelps Sam Drug Offense
不是为了我的运气,但我也想摆脱以下行:
WHERE criminal_id = 1020
以更优雅的方式代表任何与他们相关的犯罪类型超过1的犯罪分子,对于这种情况,Sam Phelps是此数据集中唯一的一个。
答案 0 :(得分:1)
正如@sgeddes在评论中所说的那样,您可以使用分析计数,如果您指定了犯罪ID,则不需要子查询:
SELECT COUNT(code_description) OVER (PARTITION BY first, last) AS "Number of Different Crimes",
last, first, code_description
FROM criminals
JOIN crimes USING (criminal_id)
JOIN crime_charges USING (crime_id)
JOIN crime_codes USING (crime_code)
WHERE criminal_id = 1020;
如果你想寻找有多种罪行的人,那么你需要一个子查询,这样你就可以过滤分析结果:
SELECT charge_count AS "Number of Different Crimes",
last, first, code_description
FROM (
SELECT COUNT(DISTINCT code_description) OVER (PARTITION BY first, last) AS charge_count,
criminal_id, last, first, code_description
FROM criminals
JOIN crimes USING (criminal_id)
JOIN crime_charges USING (crime_id)
JOIN crime_codes USING (crime_code)
)
WHERE charge_count > 1
ORDER BY criminal_id, code_description;
如果指控涉及多个犯罪,但重复,那么非重复计数仍然有效,但您可能希望为整体结果集添加一个独特的 - 除非您想显示其他犯罪特定信息 - 否则您{ {3}}