我需要一些帮助。请参考下图: -
我怎么能通过SQL这样做?
使用以下SQL: -
Select Size, Grade, sum(Qty) Qty, Price, sum(Qty*Price) Value
From TableA
Left outer join
TableB
on a.Size=b.Size and a.Grade=b.Grade
由于
答案 0 :(得分:1)
你可以这样做
WITH agg_cte AS
(
SELECT size,
SUM(CASE WHEN grade = '1' THEN qty END) qty1,
SUM(CASE WHEN grade = '2' THEN qty END) qty2
FROM tableb
GROUP BY size
), totals AS
(
SELECT size, qty1,
CASE WHEN qty2 > qty1 * 0.2 THEN qty1 * 0.2 ELSE qty2 END qty2,
CASE WHEN qty2 > qty1 * 0.2 THEN qty2 - qty1 * 0.2 ELSE 0 END qty2e
FROM agg_cte
)
SELECT p.size, p.grade,
CASE p.grade WHEN '1' THEN qty1
WHEN '2' THEN qty2
WHEN '2E' THEN qty2e
END qty,
p.price,
CASE p.grade WHEN '1' THEN qty1
WHEN '2' THEN qty2
WHEN '2E' THEN qty2e
END * p.price value
FROM TableA p JOIN totals t
ON p.size = t.size
输出:
| SIZE | GRADE | QTY | PRICE | VALUE | |-------|-------|-----|-------|-------| | 10/12 | 1 | 5 | 2.39 | 11.95 | | 10/12 | 2 | 1 | 1.79 | 1.79 | | 10/12 | 2E | 3 | 1.55 | 4.65 |
这是 SQLFiddle 演示