我有两个桌子。 表A:
Vendor Amount
001 1000
002 500
表B:
Vendor payday Amount paid
001 190101 600
001 190201 200
002 190201 100
我可以使用SQL获得以下结果
Vendor Amount payday paidamount
001 1000 190101 600
001 190201 200
002 500 190201 100
让不同数量仅显示一次吗?谢谢。
答案 0 :(得分:1)
如果RDBMS支持窗口功能,我将为此使用LAG()
,因为它避免了使用子查询:
SELECT
ta.vendor,
CASE WHEN ta.amount = LAG(ta.amount) OVER(PARTITION BY ta.vendor ORDER BY tb.payday, tb.amount DESC) THEN NULL ELSE ta.amount END amount,
tb.payday,
tb.amount
FROM tablea ta
INNER JOIN tableb tb ON ta.vendor = tb.vendor
ORDER BY
ta.vendor,
ta.amount,
tb.payday,
tb.amount
此 MySQL DB Fiddle 返回:
| vendor | amount | payday | amount |
| ------ | ------ | ------ | ------ |
| 1 | | 190101 | 200 |
| 1 | 1000 | 190101 | 600 |
| 2 | 500 | 190101 | 100 |
答案 1 :(得分:0)
使用大多数数据库管理系统支持的row_number()
select Vendor,
case when rn>1 then null else Amount end as Amount,
payday,paidamount from
(select a.Vendor,a.Amount,b.payday,b.paidamount,
row_number() over(partition by a.Vendor order by a.Amount) rn from
tableA a join tableB b on a.Vendor=b.Vendor
) t
demo link 输出
Vendor Amount payday paidamount
1 1000 190101 600
1 190101 200
2 500 190101 100
答案 2 :(得分:0)
您绝对不需要子查询来使用row_number()
:
SELECT ta.vendor,
(CASE WHEN 1 = ROW_NUMBER() OVER (PARTITION BY ta.vendor ORDER BY tb.payday, tb.amount DESC)
THEN ta.amount
END) as amount,
tb.payday, tb.amount
FROM tablea ta INNER JOIN
tableb tb
ON ta.vendor = tb.vendor
ORDER BY ta.vendor, tb.payday, tb.amount DESC;