【发布时间】:2013-06-27 13:20:19
【问题描述】:
表名和列名含糊不清,因为我从事医疗保健行业,无法分享具体细节。如果客户从我的公司(表 1)而不是他们当前的供应商(表 2)购买产品,我正在使用此查询向他们显示节省的金额。
我在 MSQL Server 2008 上有 2 个这样的表:
Table 1
ProductID、Description、Vendor、Price
Table 2
ProductID、Description、Price
我想从Table 2 中选择每一行,并从Table 1 中选择匹配数据。但是我只想从Table 1返回价格最优惠(供应商中价格最低)的供应商,而不是每个供应商。因此,对于Table 2 中的任何ProductID,应该有一个来自Table1 的匹配项,或者如果在Table 1 中没有匹配的ProductID,则为NULL 值。我加入了ProductID 上的表格并返回了我想要的所有列,但我无法将其限制为表1 中的一个结果。如果我在Table 2 中使用1000 行执行此操作,我应该返回1000 行。我一直以多个供应商匹配的一些额外内容结束。
结果应如下所示:
T1.ProductID, T1.Description, Vendor, T1.Price, T2.ProductID,
T2.Description, T2.Price, (T2.Price - T1.Price) as 'Amount Saved'
我写的SQL相当简单:
SELECT
T1.ProductID,
T1.Description,
Vendor,
T1.Price,
T2.ProductID,
T2.Description,
T2.Price,
(T2.Price - T1.Price) AS 'Amount Saved'
FROM
Table2 T2 LEFT OUTER JOIN Table1 T1
ON T2.ProductID = T1.ProductID
ORDER BY T2.ProductID
D. Stanley 的这个回答奏效了;稍作更改以选择价格最低的每一行。
SELECT
T1.ProductID,
T1.Description,
T1.Vendor,
T1.Price,
T2.ProductID,
T2.Description,
T2.Price,
(T1.Price - T2.Price) as 'Amount Saved'
FROM Table2 T2
LEFT JOIN (
SELECT * FROM (
SELECT ProductID, Description, Vendor, Price,
ROW_NUMBER() OVER (PARTITION BY ProductID ORDER BY Price ASC) AS Row
FROM Table1) as result
WHERE row=1
) AS T1
ON T2.ProductID = T1.ProductID
【问题讨论】:
-
您可以发布查询吗?
-
什么是“最佳价格”,您的意思是最低(最低)价格、最高节省等?请粘贴您尝试过的代码
标签: sql sql-server-2008 select