2016-08-24 76 views
1

所以我不确定我搞砸了多少Access SQL查询,但它相当复杂。使用Switch语句和左连接访问选择Top 1 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

酷感谢布拉德,我已经得到了语法错误,停止在治疗前1语句作为一个子查询,但现在我就奇数值是我想我只需要评估查询本身的逻辑。所以如果我需要得到我的逻辑帮助,我会提出另一个帮助问题,但是您的答案解决了语法的基本问题,谢谢! – mattlore