如何改进此查询?
select ID, Name
,(select top 1 Item FROM Items where BeneficiaryID = a.ID
order by PickupDateTime desc) as Item
,(select top 1 FontColor FROM Items where BeneficiaryID = a.ID
order by PickupDateTime desc) as FontColor
,(select top 1 BackColor FROM Items where BeneficiaryID = a.ID
order by PickupDateTime desc) as BackColor
FROM Beneficiary a
where Name like N'%Sam%'
当我尝试同一子查询中的3个字段时,我得到:
当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。
我需要获取受益人数据,其中包含存储在项目表中的最新项目。
我尝试使用左连接但没有获得所需的结果。
答案 0 :(得分:1)
struct QuestionAnswerer {
func responseTo() {
//This makes all the caracters lower cased.
let lowerQuestion = question.lowercased()
if lowerQuestion.range(of: "Photos") != nil {
myFunction()
} else {
myOtherFunction()
}
}
}
答案 1 :(得分:0)
尝试使用cte clause& ROW_NUMBER()
With itemsData as (
select BeneficiaryID, FontColor,BackColor, PickupDateTime
, row_number() over (partition by BeneficiaryID order by PickupDateTime desc) rn
From items)
Select a.ID,a.Name,b.item,b.FontColor,b.Backcolor
FROM Beneficiary a left join itemsData b on b.BeneficiaryID = a.ID and b.rn=1
where a.Name like N'%Sam%'
不带cte子句的查询
Select a.ID,a.Name,b.item,b.FontColor,b.Backcolor
FROM Beneficiary a
left join (select BeneficiaryID, FontColor,BackColor, PickupDateTime
, row_number() over (partition by BeneficiaryID order by PickupDateTime desc) rn
From items) b on b.BeneficiaryID = a.ID and b.rn=1
where a.Name like N'%Sam%'