两个表基于条件的关系

时间:2013-01-30 16:43:59

标签: sql sql-server-2005 database-design

我遇到以下情况。

我有两张表ProductsPostage

Postage

+----------------------------------+
| Weight_GM  | Postal Charges ($)  |
+----------------------------------+
|   20       |  1                  |
|   40       |  1.5                |
|   50       |  1.7                |
+----------------------------------+

Products

+-------------------------------+
| SKU   | Title     | Weight_GM |
+-------------------------------+
| ABC   | Shose     |   17      |
| JKL   | Camera    |   27      |
| XYZ   | IPad      |   48      |
+-------------------------------+

我想创建一个关系,根据两个表中定义的PostageWeight表中收取适当的邮费。

期望的结果是这样的:

+---------------------------------------------------+
| SKU   | Title     | Weight_GM | Postal Charges    |
+---------------------------------------------------+
| ABC   | Shose     |   17      |   1               |
| JKL   | Camera    |   27      |   1.5             |
| XYZ   | IPad      |   48      |   1.7             |
+---------------------------------------------------+

注意:我遇到了很多类似的问题,但没有解决我的问题。

提前致谢。

4 个答案:

答案 0 :(得分:4)

这应该有用 - 只需使用GROUP BY和MIN:

SELECT DISTINCT Pr.SKU, Pr.Title, Pr.Weight_GM, MIN(PO.Postal_Charges) as PO_Charges
FROM Products Pr
   JOIN Postage Po ON Pr.Weight_GM <= Po.Weight_GM
GROUP BY Pr.SKU, Pr.Title, Pr.Weight_GM

Fiddle

答案 1 :(得分:1)

这应该这样做

;With WeightNumber AS
(
   SELECT Weight_GM, Postal_Charge, ROW_NUMBER() OVER (ORDER BY Weight_GM) AS Num 
   FROM Postage
)
WeightRange AS
(
   SELECT ISNULL(Prec.Weight_GM - 1, 0) AS START_WEIGHT, CurrentRow.Weight_GM AS END_WEIGHT, CurrentRow.Postal_Charge
   FROM WeightNumber CurrentRow
   LEFT JOIN WeightNumber Prec
      ON Prec.Num=CurrentRow.Num - 1
)
SELECT *
FROM Products p
JOIN WeightRange w 
   ON p.Weight_GM BETWEEN w.START_WEIGHT AND w.END_WEIGHT

答案 2 :(得分:0)

您可以使用以下代码执行此操作 内部联接将使用密钥Weight_GM

连接两个表
select a.SKU, b.Postal Charges from Products a 
inner join Postage b on a.Weight_GM = b.Weight_GM

答案 3 :(得分:0)

试试这个:

select SKU,Title,prds.Weight_GM b,pst.Weight_GM a,Postal_charges
from Postage pst ,Products prds 
where prds.Weight_GM < pst.Weight_GM
group by prds.Weight_GM; 

这是演示:demo link