我有一个包含交易的表格,以及一个发布最常用信用卡的声明。 AMEX,VISA ......
SELECT CARDBRAND,
count(*) as cardused
from INFO c
left join paytb t
on c.CONT_ID = t.CONT_ID
GROUP BY CARDBRAND
ORDER BY 2 desc;
现在我想添加一个包含商店的MERCHNAME的列,这些商店最常见于与信用卡交易中的商店:
CARDBRAND CARDUSED MERCHNAME
----------------------------------------
AMEX 182345 Gasstation
VISA 70943 ....
答案 0 :(得分:1)
SELECT CARDBRAND
,count(*) as cardused
,MERCHNAME
FROM INFO c
LEFT JOIN paytb t
on c.CONT_ID = t.CONT_ID
GROUP BY CARDBRAND,
MERCHNAME
ORDER BY count(*) desc;
建议:始终建议在ORDERBY子句中使用ColumnName或函数,而不是列号,以避免混淆。
答案 1 :(得分:0)
首先,您的正确查询应为:
select c.cardbrand, count(t.cont_id) as cardused
from info c left join
paytb t
on c.cont_id = t.cont_id
group by c.cardbrand;
否则,对于未使用的卡品牌,您将永远不会获得“0”。
对于商家信息,您可以使用窗口功能:
select cardbrand, total_cardused, merchant
from (select c.cardbrand, t.merchant, count(t.cont_id) as cardused,
sum(count(t.cont_id)) over (partition by c.cardbrand) as total_cardused,
row_number() over (partition by c.cardbrand order by count(t.cont_id) desc) as seqnum
from info c left join
paytb t
on c.cont_id = t.cont_id
group by c.cardbrand, t.merchant
) cm
where seqnum = 1
group by c.cardbrand;