0
table account:
    acID (pri, uni, a-i)
    ...

table patient:
    paID (pri, uni, a-i)
    paAccountID (int, foreign key)
    ...

table test:
    tsID (pri, uni, a-i)
    tsAccountID (int, foreign key)
    tsPatientID (int, foreign key)
    tsStatus (int, ranges 0 to 3)
    tsFlag (int, ranges 0 to 1)

Retrieving data from patient and number of tsID for each patient:

SELECT patient.*, Count(tsID) as tsCount   
FROM account 
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID

Now, I would like to retrieve number of tsFlag=1, number of tsStatus=0, number of 'tsStatus=1' ... number of tsStatus=3.

Thanks to Explosion Pill's answer:

SELECT patient.*, Count(tsID), SUM(tsStatus=0), 
SUM(tsStatus=1), SUM(tsStatus=2), SUM(tsStatus=3), SUM(tsFlag=1)
FROM account 
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID

Is working like a charm, BUT giving NULL for the SUM if the Count=0 - how can I get 0 instead?

4

1 回答 1

3

You can get the count of X = Y by using a SUM:

SELECT patient.*, SUM(tsStatus = 1) AS tsStatus1
FROM ...

You can do this for the other columns as well.

You can use IFNULL or COALESCE to specify a default non-null value:

IFNULL(SUM(tsStatus = 3), 0);
于 2013-02-18T23:53:38.000 回答