我有两张桌子,第一张看起来像这样
Leave Limit
-----------------
vacation 15
sick 10
absent 9
和第二个..
Person Leave Use
-------------------------------
Chuck Norris sick 1
Bruce Lee absent 2
我想要它做的是加入表格,当我选择一个人时,它将显示如下
ex. i select Chuck Norris
Leave Limit Use
------------------------------
vacation 15 0
sick 10 1
absent 9 0
这就是我已经完成的事情......
SELECT LeavetypTbl.Leave, LeavetypTbl.Limit, ISNULL(SUM(LeaveTbl.Use), 0) AS Expr1,
LeavetypTbl.Limit- ISNULL(SUM(LeaveTbl.USE), 0) AS DayLeft
FROM LeavetypTbl LEFT OUTER JOIN
LeaveTbl ON LeavetypTbl.Leave = LeaveTbl.Leave
WHERE LeaveTbl.Person ='Chuck Norris'
GROUP BY LeavetypTbl.Leave, LeavetypTbl.Limit
但结果并不是我所期待的......很多
Leave Limit Use DayLeft
Sick 10 1 9
我只会获得1行..
答案 0 :(得分:5)
您只获得一行,因为您将结果限制为顶级'Chuck Norris'
子句中的WHERE
。但是,Chuck Norris
从未休假或缺席,因此外部联接中的其他两行被WHERE
子句消除。将其移至ON
子句以获得您期望的结果:
SELECT LeavetypTbl.Leave, LeavetypTbl.Limit, ISNULL(SUM(LeaveTbl.Use), 0) AS Expr1,
LeavetypTbl.Limit- ISNULL(SUM(LeaveTbl.USE), 0) AS DayLeft
FROM LeavetypTbl LEFT OUTER JOIN
LeaveTbl ON LeavetypTbl.Leave = LeaveTbl.Leave AND LeaveTbl.Person ='Chuck Norris'
GROUP BY LeavetypTbl.Leave, LeavetypTbl.Limit
答案 1 :(得分:3)
在JOIN条件中添加人物过滤器,如下所示:
SELECT LeavetypTbl.Leave, LeavetypTbl.Limit, ISNULL(SUM(LeaveTbl.Use), 0) AS Expr1,
LeavetypTbl.Limit- ISNULL(SUM(LeaveTbl.USE), 0) AS DayLeft
FROM LeavetypTbl LEFT OUTER JOIN
LeaveTbl ON LeavetypTbl.Leave = LeaveTbl.Leave
and LeaveTbl.Person ='Chuck Norris'
GROUP BY LeavetypTbl.Leave, LeavetypTbl.Limit