使用 Switch 语句和左连接 Access SQL 选择 Top 1
Posted
技术标签:
【中文标题】使用 Switch 语句和左连接 Access SQL 选择 Top 1【英文标题】:Select Top 1 with Switch Statement and Left join Access SQL 【发布时间】:2016-08-24 15:42:01 【问题描述】:所以我不确定我把这个 Access SQL 查询搞砸了多少,但它相当复杂。
场景如下:有三个表。一种称为“PriceMatrix”,一种称为“PreApprovedPricing”,最后一种称为“Request”。已批准的定价包含按州列出的“已批准”价格列表,“价格矩阵”包含从另一个来源生成的价格列表,请求是所有这些都指向的父记录(也包含州)。我正在尝试编写一个查询来比较每个表中的价格,如果预先批准的价格小于价格矩阵中的价格,它会替换字段中的值,但如果大于,则保留原价矩阵价格。我尝试使用 switch 语句来查看给定的状态。
这是我的查询:
SELECT TOP 1 [ApprovedPrice] from [PreApprovedPricing] AS [1stMonthApproved] WHERE [ApprovedPrice] >= [PriceMatrix].[1stMonth]
ORDER BY [ApprovedPrice] ASC,
SWITCH( Request.[state] = 'CT' , [1stMonthApproved], Request.[state] = 'MA' , [1stMonthApproved], 1=1 , [PriceMatrix].[1stMonth]) AS 1stMonth,
FROM PriceMatrix LEFT JOIN Request ON PriceMatrix.RequestID = Request.RequestID;
我不断收到语法错误,但我似乎无法深入了解问题的根源。所以任何输入都会很棒,因为我还在学习 SQL
【问题讨论】:
【参考方案1】:您不能有多个 From 子句。你的陈述
SELECT TOP 1 [ApprovedPrice]
from [PreApprovedPricing] AS [1stMonthApproved]
WHERE [ApprovedPrice] >= [PriceMatrix].[1stMonth]
ORDER BY [ApprovedPrice] ASC,
SWITCH( Request.[state] = 'CT' , [1stMonthApproved], Request.[state] = 'MA' , [1stMonthApproved], 1=1 , [PriceMatrix].[1stMonth]) AS 1stMonth,
FROM PriceMatrix
LEFT JOIN Request ON PriceMatrix.RequestID = Request.RequestID;
其实是:
Select Top
From
Where
Order by
From
Left Join
那肯定会出现语法错误。我假设您想要在某个地方进行子查询。也许像这样(但很难确定):
SELECT [ApprovedPrice] ,
(Select top 1 SWITCH( Request.[state] = 'CT' , [1stMonthApproved], Request.[state] = 'MA' , [1stMonthApproved], 1=1 , [PriceMatrix].[1stMonth])
from [PreApprovedPricing] AS [1stMonthApproved]
WHERE [ApprovedPrice] >= [PriceMatrix].[1stMonth]
ORDER BY [ApprovedPrice] ASC,
SWITCH( Request.[state] = 'CT' , [1stMonthApproved], Request.[state] = 'MA' , [1stMonthApproved], 1=1 , [PriceMatrix].[1stMonth])) AS 1stMonth
FROM PriceMatrix
LEFT JOIN Request ON PriceMatrix.RequestID = Request.RequestID;
【讨论】:
酷谢谢布拉德,我已经得到了语法错误,停止将前 1 条语句视为子查询,但现在我得到奇怪的值,我认为我只需要评估逻辑查询本身。所以如果我需要我的逻辑方面的帮助,我会提出另一个帮助问题,但你的回答解决了语法的根本问题,谢谢!以上是关于使用 Switch 语句和左连接 Access SQL 选择 Top 1的主要内容,如果未能解决你的问题,请参考以下文章