2

我陷入以下情况。

我有两张桌子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      |
+-------------------------------+

我想创建一个关系以根据两个表中定义的表从Postage表中收取适当的邮政费用。Weight

期望的结果是这样的:

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

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

提前致谢。

4

4 回答 4

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

还有小提琴

于 2013-01-30T16:56:50.530 回答
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
于 2013-01-30T17:00:18.983 回答
0

您可以使用以下代码执行此操作 内部连接将使用键 Weight_GM 连接两个表

select a.SKU, b.Postal Charges from Products a 
inner join Postage b on a.Weight_GM = b.Weight_GM
于 2013-01-30T16:49:43.450 回答
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; 

这是演示:演示链接

于 2013-01-30T17:43:50.100 回答