使用按日期过滤来连接多个表

时间:2016-01-02 15:42:47

标签: sql sql-server view

我有3张桌子。我如何加入这些表格,并在每张桌子上按日期过滤

MainTbl

 id    accnt   amount    date
---------------------------------
  1      xxx     10.00   1/1/2016
  2      yyy     20.00   1/1/2016
  3      zzz     30.00   1/1/2016

SupplyTbl - 此表会将供应值添加到MainTbl

中的金额
  id   accnt    supply   date
-------------------------------
   1     xxx     5.00     1/10/2016
   1     xxx     5.00     2/14/2016
   2     yyy    10.00     1/20/2016

IssuedTbl

  id   accnt    issued   dateIssue
------------------------------------------
   1     xxx    5.00      1/10/2016
   1     xxx    5.00      2/14/2016
   2     yyy   10.00      2/15/2016  

现在我想加入这些表..日期范围..如果我将日期过滤到JANUARY,它会产生类似这样的结果

  id   accnt  amount   issued
 -----------------------------
  1     xxx    15.00    5.00
  2     yyy    30.00    0.00
  3     zzz    30.00    0.00

当我过滤到FEBRUARY时,它会合并JANUARYFEBRUARY

 id   accnt  amount   issued
 -----------------------------
  1     xxx    20.00   10.00
  2     yyy    40.00   10.00
  3     zzz    30.00    0.00
从那天晚上起我就一直在努力奋斗..很高兴有任何帮助..提前知道:)

1 个答案:

答案 0 :(得分:2)

尝试这样的事情

SELECT M.id, 
       M.accnt, 
       amount = M.amount + Isnull(s.supply, 0), 
       issued = Isnull(I.issued, 0) 
FROM   maintbl M 
       LEFT OUTER JOIN (SELECT id, 
                               Sum(supply) AS supply 
                        FROM   supplytbl 
                        WHERE  Month(dates) = 1  -- Month filter for Jan - feb Month(dates) in (1,2)
                        GROUP  BY id) S 
                    ON s.id = M.id 
       LEFT OUTER JOIN (SELECT id, 
                               Sum(issued) AS issued 
                        FROM   issuedtbl 
                        WHERE  Month(dateissue) = 1 -- Month filter
                        GROUP  BY id) I 
                    ON I.id = M.id