kodcu kodcu - 11 days ago 5
MySQL Question

Count field and group by regarding another field on same table MySQL

I am trying to find count of field by another field in same table on MySQL.My Table Like This:

Id DrgId CodeType IsPrincipal Code
182250051 48261836 I 1 T151
182250055 48261836 I 2 U739
182250059 48261836 I 3 Y929
182250061 48261836 I 4 W444
182250062 48261836 A 2 3006104


So I want to find used helper codes for T151 which is IsPrincipal equals 1.

Output should like this:

Code Helper_I_Count Helper_A_Count
T151 3 1


So I tried Like this:

SELECT t.`Code`,COUNT(v1.`Code`) AS EkTaniSay,COUNT(v2.`Code`) AS IslemSay
FROM TIGPatientCode t,
(
SELECT DRGPatientId,`Code`
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='I'
) v1,
(
SELECT DRGPatientId,`Code`
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='A'
) v2
WHERE t.IsPrincipal='1' AND t.DRGPatientId=v1.DRGPatientId AND t.DRGPatientId=v2.DRGPatientId
GROUP BY t.`Code`


But it wont get actual count.

How can I Do this?

Thanks

Answer
SELECT t2.Code, 
        SUM(t1.CodeType = 'I') AS EkTaniSay,
        SUM(t1.CodeType = 'A') AS IslemSay
FROM TIGPatientCode AS t1
RIGHT JOIN TIGPatientCode AS t2 ON t1.DrgPatientId = t2.DrgPatientId
WHERE t1.isPrincipal != 1 AND t2.isPrincipal = 1
GROUP BY t1.DrgPatientId;

The first part of the query is based on multiple query same table but in different columns mysql. Then I join this with the table again to get the code for the principal row.

The problem with your query is that joining the two subqueries creates a cross-product of all the rows, which causes the counts to be multiplied. Also, if there's any group that doesn't have one of the codes, that subquery will return no rows, so the join will be empty for that code. You could fix the first problem by doing the counts in the subqueries rather than the main query. The second problem can be fixed by using LEFT JOIN. So the fixed version of your query would look like:

SELECT t.Code, v1.EkTaniSay, v2.IslemSay
FROM TIGPatientCode t
LEFT JOIN (
    SELECT DRGPatientId, COUNT(*) AS EkTaniSay
    FROM TIGPatientCode
    WHERE IsPrincipal<>'1' AND CodeType='I'
    GROUP BY DRGPatientId
) AS v2 ON t.DRGPatientId = v2.DRGPatientId
LEFT JOIN (
    SELECT DRGPatientId, COUNT(*) AS IslemSay
    FROM TIGPatientCode
    WHERE IsPrincipal<>'1' AND CodeType='A'
    GROUP BY DRGPatientId
) AS v1 ON t.DRGPatientId = v1.DRGPatientId
WHERE t.IsPrincipal = 1

DEMO

Comments