我試圖在不使用子查詢的情況下實現以下功能。關於SQL分組的問題
對於資金來說,我想選擇最新的Letter創建日期和'創建信件之後創建的最早的工作列表'以獲得資助。
FundingId Leter (1, 1/1/2009)(1, 5/5/2009) (1, 8/8/2009) (2, 3/3/2009) FundingId WorkList (1, 5/5/2009) (1, 9/9/2009) (1, 10/10/2009) (2, 2/2/2009)
預期結果 -
FundingId Leter WorkList (1, 8/8/2009, 9/9/2009)
我寫了一個查詢,如下所示。它有一個錯誤。它將省略那些最低工作清單日期少於最新信函日期(儘管它的工作清單大於信件創建日期)的FundingId。
CREATE TABLE #Funding(
[Funding_ID] [int] IDENTITY(1,1) NOT NULL,
[Funding_No] [int] NOT NULL,
CONSTRAINT [PK_Center_Center_ID] PRIMARY KEY NONCLUSTERED ([Funding_ID] ASC)
) ON [PRIMARY]
CREATE TABLE #Letter(
[Letter_ID] [int] IDENTITY(1,1) NOT NULL,
[Funding_ID] [int] NOT NULL,
[CreatedDt] [SMALLDATETIME],
CONSTRAINT [PK_Letter_Letter_ID] PRIMARY KEY NONCLUSTERED ([Letter_ID] ASC)
) ON [PRIMARY]
CREATE TABLE #WorkList(
[WorkList_ID] [int] IDENTITY(1,1) NOT NULL,
[Funding_ID] [int] NOT NULL,
[CreatedDt] [SMALLDATETIME],
CONSTRAINT [PK_WorkList_WorkList_ID] PRIMARY KEY NONCLUSTERED ([WorkList_ID] ASC)
) ON [PRIMARY]
SELECT F.Funding_ID,
Funding_No,
MAX (L.CreatedDt),
MIN(W.CreatedDt)
FROM #Funding F
INNER JOIN #Letter L ON L.Funding_ID = F.Funding_ID
LEFT OUTER JOIN #WorkList W ON W.Funding_ID = F.Funding_ID
GROUP BY F.Funding_ID,Funding_No
HAVING MIN(W.CreatedDt) > MAX (L.CreatedDt)
如何在不使用子查詢的情況下編寫正確的查詢?
請幫
感謝
Lijo
是這個sql服務器? – 2010-03-19 13:08:10
是的。它在SQL Server 2005中 – Lijo 2010-03-22 07:13:28