2014-01-16 67 views
0

我有這樣的SQL查詢總結多表父子關係的公共列在SQL Server

SELECT  dbo.a.Agency, SUM(COALESCE (dbo.b.total, 0)) + SUM(COALESCE (dbo.c.total, 0)) 
        + SUM(COALESCE (dbo.d.total, 0)) AS Expr1, 
dbo.b.date as date, 
dbo.c.Date AS Expr2, 
dbo.d.Date AS Expr3 
FROM   dbo.c RIGHT OUTER JOIN 
        dbo.a ON dbo.d.Agency = dbo.a.Agency LEFT OUTER JOIN 
        dbo.c ON dbo.a.Agency = dbo.c.Agency LEFT OUTER JOIN 
        dbo.b ON dbo.a.Agency = dbo.b.Agency 
GROUP BY dbo.a.Agency, dbo.b.Date, dbo.c.Date, dbo.d.Date 

我想實現的是組在同一時間3個日期字段。所以結果看起來像這樣

+------+-------+----+ 
|Agency|expr1 |Date| 
+------+-------+----+ 
|abc |500000 |18 | 
+------+-------+----+ 
|def |6000000|18 | 
+------+-------+----+ 
|abc |550000 |19 | 
+------+-------+----+ 
|def |750000 |19 | 
+------+-------+----+ 

日期只是包含int值,如示例演示。他們被鏈接到另一個可以使用的表格,如果這更容易。

當前的代碼只顯示每行的每個日期值的1行。如果我使用的過濾器使用ANDOR它顯示不正確的結果

回答

0

沒關係。我通過使用交叉應用並在where子句中使用Date = 21來解決此問題