我有一個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))";
我是寫mysql的,給你參考看看
SELECT Product_name
FROM Cart
WHERE Customer_id='x'
GROUP BY Product_name
ORDER BY COUNT(*) DESC
Limit 1
請參閱 : 趣味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
剩下的想怎麼改就怎麼改吧
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漏了別名設定吧~
錯誤
正確