Roman
Roman

Reputation: 1121

how to join two tables and count occurrences some values?

I am asking to for a help because I do not know SQL very well.

I need to join two tables and count occurrences some values from second table to achieve effect like statistics table which will have coluns:

Result Table:

My Result Table needs to have first two columns (contry and site) comes from first table "Violations" and next 5 columns which will contain numbers (count) of occurrences status_id in "Violations" in each of possible values of id from Status table.

Now I can upload image of table result what I want to achieve: Result Table

So, I have existing two tables: Violations and Status.

Violations:

Status:

In result of my join is to have table which should contain columns:

My pseudo code and abstract try:

SELECT v.country, v.site, count(v.status_id == 1), count(v.status_id == 2), count(v.status_id == 3), count(v.status_id == 4)
FROM Violations v JOIN Status s 
ON v.status_id=s.id
GROUP BY v.country, v.site

Pleas help me to write correct sql query, because have big problem to do that.

Upvotes: 0

Views: 4041

Answers (1)

Taryn
Taryn

Reputation: 247680

You should be able to use an aggregate function with a CASE expression to get the result:

select v.country,
    v.site,
    SUM(case when s.id = 1 then 1 else 0 end) Total_SuspectedViolations,
    SUM(case when s.id = 2 then 1 else 0 end) Total_ConfirmedViolations,
    SUM(case when s.id = 3 then 1 else 0 end) Total_ConfirmedNoViolations,
    SUM(case when s.id = 4 then 1 else 0 end) Total_NotDetermined,
    COUNT(*) Total
from violations v
inner join status s
    on v.status_id = s.id
group by v.country, v.site

See SQL Fiddle with Demo

This can also be written without the JOIN:

select v.country,
    v.site,
    SUM(case when v.status_id = 1 then 1 else 0 end) Total_SuspectedViolations,
    SUM(case when v.status_id = 2 then 1 else 0 end) Total_ConfirmedViolations,
    SUM(case when v.status_id = 3 then 1 else 0 end) Total_ConfirmedNoViolations,
    SUM(case when v.status_id = 4 then 1 else 0 end) Total_NotDetermined,
    COUNT(*) Total
from violations v
group by v.country, v.site

See SQL Fiddle with Demo

Upvotes: 2

Related Questions