另一个查询问题

时间:2015-03-12 15:55:03

标签: sql vb.net

我的第一张桌子

type         days        application
-------------------------------
sick          10         leave
vacation      10         leave
PSCS           0         Seminar

我的第二张表

person             type           UseDays
-----------------------------------------
chuck norris      vacation             1
chuck norris      PSCS                 0
bruce lee         sick                 5

我希望加入他们..但我想只查看'离开'在第一个表格字段中的应用

离。我选择了查克诺里斯

type          days          UseDays
------------------------------------
sick           10                 0
vacation       10                 1

这是我已经做过的事情......但仍然无法做正确的事情......

SELECT      LeavetypTbl.Id, LeavetypTbl.type , LeavetypTbl.days, ISNULL(SUM(LeaveTbl.UseDays), 0) AS Expr1, LeavetypTbl.days- ISNULL(SUM(LeaveTbl.UseDays), 0) as LeftX " & _
FROM        LeavetypTbl " & _
LEFT OUTER JOIN " & _
LeaveTbl " & _
ON          LeavetypTbl.type = LeaveTbl.type And LeaveTbl.IDno = '" & id & "' and LeaveTbl.Application <> 'Seminar'" & _
GROUP BY    LeavetypTbl.type , LeavetypTbl.days, LeavetypTbl.Id"

并且结果...仍将显示所有应用程序类型..

1 个答案:

答案 0 :(得分:2)

采取较小的步骤。让我们从您想要显示的类型开始。我们在leave上过滤这些内容。我们将此结果称为A

type         days        application
-------------------------------
sick          10         leave
vacation      10         leave

现在让我们看看第二个表并在相关人员上过滤它:

person             type           UseDays
-----------------------------------------
chuck norris      vacation             1
chuck norris      PSCS                 0

现在我们总结一下UseDays,因为可能会有很多假期。结果看起来非常相似。我们称之为B

person             type      SumOfUseDays
-----------------------------------------
chuck norris      vacation             1
chuck norris      PSCS                 0

你知道如何达到这一点,对吧?现在让我们在AB)上加入typeSELECT ... FROM (...select-for-a...) AS A LEFT JOIN (...select-for-b...) AS B ON A.type = B.type。确保使用LEFT JOIN,因为我们想要A中的所有记录,即使B中没有记录也存在:

type         days        application person      SumOfUseDays
-------------------------------------------------------
sick          10         leave       NULL              NULL
vacation      10         leave       chuck norris      1

我们不需要person列,所以我们放弃它。我们在SumOfUseDays中仍然有这个丑陋的NULL,所以我们将COALESCE或ISNULL的结果归结为0:

type         days        application SumOfUseDays
-------------------------------------------------
sick          10         leave             0
vacation      10         leave             1

我们有。实施留作练习,但随时可以询问您是否遇到特定步骤。