如何在两个SQL表中聚合计数?

时间:2013-05-24 21:15:22

标签: sql database

我有两张这样的表

Table 1: MedicineType  
MedicineTypeID MedicineTypeName
TE001         | HIV
TE002         | AIDS

Table 2: MsMedicine
MedicineID MedicineTypeID MedicineName
ME001     | TE001        | HIVgood 
ME002     | TE001        | HIVsmart
ME003     | TE002        | AIDSawesome

如何显示MedicineTypeID,MedicineTypeName和MedicineCount(从每个MedicineType上的MedicineID数量派生) 例如:

MedicineTypeID MedicineTypeName MedicineCount
        TE001 | HIV            | 2
        TE002 | AIDS           | 1

2 个答案:

答案 0 :(得分:3)

Select mt.MedicineTypeID, mt.MedicineTypeName, Count(m.MedicineID) as MedicineCount
From MedicineType
Inner Join MSMedicine m On mt.MedicineTypeID = m.MedicineTypeID
Group By mt.MedicineTypeID, mt.MedicineTypeName

答案 1 :(得分:0)

从MedicineType中选择MedicineTypeID,MedicineTypeName,count(*)作为MedicineCount,在MedicineType上连接MsMedicine.MedicineID = MedicineTypeID的MedMedicine.MedicineID group,MedicineTypeName