0

i have an issue with query

1st table (Master) Name :MainCategory with fields (Category_id,Category_name)

2nd Table (Transation) Name : Incident with fields (Incident_id,Category_id,subject,description)

i want to query to count the appearance of category_id in the table Transation

for eg result can be

Category_name   Number_of_Faults

Hardware          10
Software          22
Network           17

thanks

Kumar

2 Answers 2

2

Try this:

SELECT a.Category_Name, COUNT(b.Incident_Id) Number_of_Faults
FROM MainCategory a JOIN Incident b
ON a.Category_id = b.Category_id
GROUP BY a.Category_Name
Sign up to request clarification or add additional context in comments.

7 Comments

In many RDBM systems, one has to write: GROUP BY a.Category_id, a.Category_Name
@ypercube: You're right, but OP didn't tell us which SQL type he's using... so I tried this believing it could be correct. Thanks :)
@Marco: Most RDBMS will reject this GROUP BY because it doesn't match the SELECT list. IIRC, only MySQL allows such ambiguity
@Marco: It was not wrong before. But it would only work in systems (like MySQL) that support the inclusion (in the Select list) of fields that are functionally dependent on the fields in Group by list.
@gbn: It's not ambiguity when a.Category_id is primary key and (therefore) a.Category_name is functionally dependent on it.
|
2

Try this. You need a LEFT JOIN to deal with "no incidents" for a given category

SELECT
    M.Category_Name,
    COUNT(I.Category_id) AS Number_of_Faults
FROM
    MainCategory M
    LEFT JOIN
    Incident I ON M.Category_id = I.Category_id
GROUP BY
    M.Category_name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.