我需要对一些数据进行分组,但因为有4个商店图像,sql查询会为每个商店返回4个结果。如何通过使用SQL查询只获得一个商店?
select s.name,si.SHOP_IMG_PATH,count(*) amount from stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name,si.SHOP_IMG_PATH
order by 3 desc,1 asc
如下图所示,有4张图片,因此查询可以提供随机图片
答案 0 :(得分:1)
group by s.name, si.SHOP_IMG_PATH
你告诉它根据SHOP_IMG_PATH
来区分它们。因此,它显示了4个结果,每个结果一个。
如果你不让它使用,你必须从SHOP_IMG_PATH
条款中删除select
。
得到你的评论。您正在寻找的是随机聚合。这在不同的SQL引擎上有所不同。 Google就是你正在使用的那个。
如果是Oracle,则问题标记为here
答案 1 :(得分:1)
您正在按照s.name,si.SHOP_IMG_PATH进行分组,它会将s.name,si.SHOP_IMG_PATH的所有可能组合视为单独的,您需要仅通过s.name保留组
试试这个
SELECT a.NAME, a.PATH, a.AMOUNT
FROM (select
s.name AS 'NAME', si.SHOP_IMG_PATH AS 'PATH', count(*) AS 'AMOUNT',
ROW_NUMBER() OVER(PARTITION BY s.name
ORDER BY type si.SHOP_IMG_PATH) AS rk
from
stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name
order by 3 desc,1 asc) a
WHERE a.rk = 1;
替代 你会得到结果,但这只是一个解决方法,可以轻松替代你的问题而不是一个好的。
select s.name AS 'NAME', min(si.SHOP_IMG_PATH) AS 'PATH', count(*) AS 'AMOUNT',
from
stab t
inner join shop s on (s.shop_id = t.shop_id)
inner join SHOP_IMG si on (s.shop_id= si.SHOP_ID)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name
order by 3 desc,1 asc
第二个查询将根据您的需要返回结果
答案 2 :(得分:0)
我使用以下查询解决了我的问题,
select s.name,t.shop_id,(select min(SHOP_IMG_PATH) from SHOP_IMG si where shop_id =t.shop_id),count(*) amount from stab t
inner join shop s on (s.shop_id = t.shop_id)
where t.acct_id = 111 and t.CR_DATE >= sysDate - 1
group by s.name,t.shop_id
order by 4 desc,1 asc