iT邦幫忙

1

請教SQL大師,如何在GROUP BY分群裡 找出組別最多筆數量的組別名稱

我有一個Table 是Cart(Cart_id,Customer_id,pid,Product_name,Price)
問題是 給定Customer_id=x我想找出x加入購物車最多次的產品名稱(Product_name)

下面是我下的指令
目前我的思路是用子搜尋的方式一邊找所有可能性一邊找max count進行比對
不過c#不給過,求解!

"SELECT Product_name
FROM  Cart
WHERE Customer_id='x' GROUP BY Product_name 
HAVING COUNT(Product_name) = 
(SELECT MAX(mycount) FROM (SELECT Product_name, COUNT(Product_name) AS mycount FROM Cart GROUP BY Product_name))";
1.order by 資料 ( group by 結果) 之後取第一筆,結束。
2.原語法思路是在繞圈圈,您有確定這個SQL語法直接在DB執行可以成功拿到你要的答案嗎? SQL請直接在DB執行測試過
3.不同DB的SQL有些部分會略有落差,不是一體適用,建議先附上您的DB種類跟版本
e6319a5b iT邦新手 4 級 ‧ 2022-01-10 22:32:34 檢舉
了解,謝謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
3
breakgod
iT邦新手 2 級 ‧ 2022-01-10 08:38:03
最佳解答

我是寫mysql的,給你參考看看

SELECT Product_name
FROM Cart
WHERE Customer_id='x'
GROUP BY Product_name
ORDER BY COUNT(*) DESC
Limit 1
1
rogeryao
iT邦超人 8 級 ‧ 2022-01-09 19:45:26

請參閱 : 趣味SQL,求出前十大客戶各自的前十大商品合計銷售額

修改為 MS SQL 前 10 大交易筆數的個別前 3 名

SELECT *
FROM (
SELECT *,Dense_Rank() OVER (ORDER BY SUBTOTAL DESC,custid) AS NO2
FROM (
SELECT custid,productid,amount,
SUM(amount) OVER (PARTITION BY custid) AS SUBTOTAL,
ROW_NUMBER() OVER (PARTITION BY custid ORDER BY amount DESC) AS NO
FROM (
-- SELECT custid,productid,SUM(amount) AS amount
SELECT custid,productid,SUM(1) AS amount
FROM temp
GROUP BY custid,productid
) AS K
) AS Q
WHERE Q.NO<=3) AS S
WHERE S.NO2<=10

Demo

剩下的想怎麼改就怎麼改吧

e6319a5b iT邦新手 4 級 ‧ 2022-01-09 19:56:00 檢舉

實在抱歉 我剛摸SQL不久,看不太懂上面的寫法...

5
純真的人
iT邦大師 1 級 ‧ 2022-01-10 09:53:17

MSSQL參考

declare @Cart table(
	Cart_id int
	,Customer_id varchar(50)
	,pid int
	,Product_name nvarchar(50)
	,Price int
)
insert into @Cart
values('1','x',1,'IT1',500)
,('2','v',1,'IT1',500)
,('3','x',2,'IT2',500)
,('4','x',2,'IT2',500)
,('5','x',1,'IT1',500)
,('6','x',1,'IT1',500)
,('7','x',1,'IT1',500)

SELECT top 1 Product_name
FROM  @Cart
WHERE Customer_id='x' 
group by Product_name
order by count(0) desc

話說C#不給過~大概是因為你在having語句裡面的from漏了別名設定吧~
錯誤
https://ithelp.ithome.com.tw/upload/images/20220110/20061369oYxpfP5LLH.png
正確
https://ithelp.ithome.com.tw/upload/images/20220110/20061369xwpwhfb0qS.png

e6319a5b iT邦新手 4 級 ‧ 2022-01-10 22:32:22 檢舉

非常感謝你的熱心留言!

我要發表回答

立即登入回答