SQL Server How to count/classify specific records in a one to many relationship?

dsf9zpds  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(148)


Thanks so much for your continued assistance. I'm hoping to create a list of counties that my staff serve, and a column for the number of Misdemeanor Investigations, and another for the number of Felony Investigations. The Pending Charge and Court tables are outlined below. Court is the parent for Pending Charges and the CourtID Column of the Pending Charge table is = to the ID column of the Court table, i.e. JOIN vPendingCharges pc ON pc.CourtID = c.ID.

Court table:
| ID | DefendantID | CountyID |
| ------------ | ------------ | ------------ |
| 00035ed9 | 2a1e50f9 | Haus County |
| 000b2a8c | F3dc3251 | Saul County |

Pending Charge table:

IDDefendantIDCourtIDClass
9f78778d2a1e50f900035ed93
a53a48412a1e50f900035ed92
a9d2c5a2F3dc3251000b2a8cA
daf26cb0F3dc3251000b2a8cA

Desired Output:

CountyNumber FelonyNumber Misdemeanor
Haus County10
Saul County01

I too will fiddle with what you already provided which is great. Maybe by some miracle I get to where I want to go first!?. Thanks again for all your assistance.

piztneat

piztneat1#

You can use a subquery or CTE as a helper. ie:

  1. select ChargeType, count(*)
  2. from (
  3. Select case
  4. when exists (select * from Charges ch
  5. where ch.CourtId = c.CourtId and ch.Class in ('A','B', 'C'))
  6. then 'Misdemeanors' else 'Felony' end as ChargeType
  7. from Courts c
  8. ) tmp
  9. group by ChargeType;

EDIT:

  1. WITH tmp AS (SELECT CountyID, CASE WHEN EXISTS
  2. (SELECT *
  3. FROM PendingCharge AS pc
  4. WHERE c.ID=pc.CourtID AND pc.Class IN ('M', 'X', '1', '2', '3', '4'))
  5. THEN 'Felony'
  6. ELSE 'Misdemeanor'
  7. END AS ChargeType
  8. FROM Court AS c)
  9. SELECT CountyID,
  10. SUM(CASE WHEN ChargeType='Felony' THEN 1 ELSE 0 END) AS [Number Felony],
  11. SUM(CASE WHEN ChargeType='Misdemeanor' THEN 1 ELSE 0 END) AS [Number Misdemeanor]
  12. FROM tmp
  13. GROUP BY CountyID;

And here is DBFiddle demo.

展开查看全部

相关问题