在sql server中总结多表父子关系的公共列

时间:2014-01-16 03:33:21

标签: sql sql-server

我有这个SQL查询

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  |
+------+-------+----+

Date仅包含int值,如示例所示。它们链接到另一个表,如果这更容易,可以使用它。

当前代码仅为每个表的每个日期值显示1行。如果我使用ANDOR过滤器,则会显示不正确的结果

1 个答案:

答案 0 :(得分:0)

没关系。我通过使用交叉应用并在where子句

中使用Date = 21来解决它