我基本上需要做兩個表(CarePlan和推薦)的左外連接問題是我需要最新的推薦如果它存在,它的好如果沒有。SQL Server:左頂部加入頂部1以選擇最多一行
我有這2個查詢 1.加入CarePlan /推薦表 - 創建重複careplans如果有一個careplan多個引用,或具有完全沒有轉診信息(左外連接) 2.選擇頂部1根據日推薦,給予CarePlanId
我想這兩個,所以我抓住所有的careplans和轉診如果它存在,如果它不合並 - 只需要最新的轉診
select * from CarePlan c //query 1
left outer join Referral r on
r.CarePlanId = c.CarePlanId
select top 1 * from Referral r //query 2
where r.CarePlanId = '1'
order by ReferralDate desc
編輯:
第一個查詢給了我這樣的事情:
CarePlanID ReferralId ReferralDate
---------- ---------- ------------
1 1 05/15/12
2 NULL NULL
1 2 05/10/12 //Old date, dont want this careplan
第二個查詢會給我與最新的日期
ReferralId ReferralDate
---------- ------------
1 05/15/12
引薦數據轉診,可以有0個或多個轉介屬於Careplan
ReferralID CarePlanId Date
---------- ---------- ----
1 1 05/15/12
2 1 05/10/12
最後,我希望有一個查詢,讓我與擁有最新的日期,或者爲null,推薦,如果它不必須請示careplans它
這樣的:
CarePlanId ReferralId ReferralDate
---------- ---------- ------------
1 1 05/15/12
2 NULL NULL
謝謝 - 我希望這是有道理
有困難readin什麼喲想,但我認爲你需要的是查找如何做cte或派生表。 – HLGEM 2012-03-06 22:25:06
你能展示樣本數據和期望的結果嗎?像@HLGEM一樣,你不清楚你開始的地方以及你想要結束的地方。 – 2012-03-06 22:30:47
您需要交叉申請。 – usr 2012-03-06 22:33:16