這是Summing common columns of multi table parent-child relation的直接後續。總結多表格親子關係第2部分的公共列
表格佈局是:
CREATE TABLE [dbo].[a]
[primary_key] [nvarchar](7) NOT NULL
CREATE TABLE [dbo].[b]
[column1] [nvarchar](7) NOT NULL
[column2] [int] NOT NULL
[column3] [int] not null
CREATE TABLE [dbo].[c]
[column1] [nvarchar](7) NOT NULL
[column2] [int] NOT NULL
[column3] [int] not null
CREATE TABLE [dbo].[d]
[column1] [nvarchar](7) NOT NULL
[column2] [int] NOT NULL
[column3] [int] not null
CREATE TABLE [dbo].[DateTable]
[index] [int] NOT NULL
[date] [date] NOT NULL
這是大致的設計。我有1對父母和3個孩子中,我用這個sql查詢總結了3行
SELECT a.primary_key,
b.Sum AS Expr1,
c.Sum AS Expr2,
d.Sum AS Expr3,
ISNULL(b.Sum, 0) + ISNULL(c.Sum, 0) + ISNULL(d.Sum, 0) as [GrandTotal]
FROM dbo.Agency_Table a
OUTER APPLY (SELECT SUM(ISNULL(b.column2, 0)) [Sum] FROM dbo.b WHERE a.primary_key = b.column1) as b
OUTER APPLY (SELECT SUM(ISNULL(c.column2, 0)) [Sum] FROM dbo.c WHERE a.primary_key = c.column1) as c
OUTER APPLY (SELECT SUM(ISNULL(d.column2, 0)) [Sum] FROM dbo.d WHERE a.primary_key = d.column1 as d
現在我要實現的是用b,c和d的3列是一個int上次查詢連接到日期表(E)的字段。我想按日期分組。這可以通過在int上進行分組來完成,但最好由實際日期進行分組。所以有效地將數據庫想象成與父母無關的父母表,然後是其3個孩子。
我設想是這樣的
SELECT a.primary_key,
b.Sum AS Expr1,
c.Sum AS Expr2,
d.Sum AS Expr3,
dbo.dateTable.Date
ISNULL(b.Sum, 0) + ISNULL(c.Sum, 0) + ISNULL(d.Sum, 0) as [GrandTotal]
FROM dbo.Agency_Table a
OUTER APPLY (SELECT SUM(ISNULL(b.column2, 0)) [Sum] FROM dbo.b WHERE a.primary_key = b.column1) as b
OUTER APPLY (SELECT SUM(ISNULL(c.column2, 0)) [Sum] FROM dbo.c WHERE a.primary_key = c.column1) as c
OUTER APPLY (SELECT SUM(ISNULL(d.column2, 0)) [Sum] FROM dbo.d WHERE a.primary_key = d.column1 as d
//some kind of join to the next table
INNER JOIN dbo.b ON dbo.Date.index = dbo.b.Column3
INNER JOIN dbo.c ON dbo.Date.index = dbo.c.column3
INNER JOIN dbo.d ON dbo.Date.index = dbo.d.column3
group by dbo.dateTable.Date?
對不起事先我覺得像即時得到你做我的工作。
這是SQL Server 2012
提示:我們中的一些人可以讀取TSQL語句,例如CREATE TABLE比詩歌更容易。這將是一個更好的方式來描述你的表格及其關係。 – HABO
我確實寫了一些很好的詩 – TXL