选择Top 1 with Switch Statement和Left join Access SQL

时间:2016-08-24 15:42:02

标签: sql ms-access

所以我不确定我已经搞砸了这个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 个答案:

答案 0 :(得分: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;