开发者

mysql join count

开发者 https://www.devze.com 2023-01-17 21:03 出处:网络
I have two table Table Leave ID| TYPE 1Annual 2Sick 3Unpaid 4Marriage Table LeaveData IDLEAVEDATA| LEAVETYPE*

I have two table

Table Leave

ID   | TYPE
1      Annual 
2      Sick 
3      Unpaid
4      Marriage

Table LeaveData

IDLEAVEDATA   | LEAVETYPE*
1                 1      
2                 开发者_如何学运维1
3                 2
4                 2

LEAVETYPE is foreign key (refer to ID in table leave)

How do i count the occurence of ID in table LeaveData?

Output example :

TYPE         |  COUNT
Annual          2
Sick            2
Unpaid          0 or null
Marriage        0 or null


Try this:

 SELECT  L.[Type] AS [Type]
         ,ISNULL(COUNT(*),0) AS [Count]
 FROM    Leave AS L
 LEFT JOIN LeaveData AS LD ON LD.LeaveType = L.ID
 ORDER BY 2 DESC


try,

SELECT  l.TYPE , COUNT(ld.LEAVETYPE) as COUNT
FROM    Leave AS l
LEFT JOIN LeaveData AS ld ON ld.LEAVETYPE = L.ID
GROUP BY  ld.LEAVETYPE
0

精彩评论

暂无评论...
验证码 换一张
取 消