查询表中具有最高计数的ID的SQL语句。

huangapple go评论65阅读模式
英文:

SQL to query the id with the most count in a table

问题

我有这些表格:

查询表中具有最高计数的ID的SQL语句。

我想查询特定月份(任何月份)中购买量最多的商店ID。我提出了以下查询:

SELECT DISTINCT store_id FROM (SELECT store_id, purchase_date FROM purchase WHERE purchase_date >= '2021-04-01' AND purchase_date <= '2021-04-30';

SELECT DISTINCT store)

我在SQL方面还是初学者,似乎无法继续前进。

英文:

I have these tables here:

查询表中具有最高计数的ID的SQL语句。

and I want to query the store ID with the most purchases in a specific month (any month).
I came up with this query:

SELECT DISTINCT store_id FROM (SELECT store_id, purchase_date FROM purchase where purchase_date &gt;= &#39;2021-04-01&#39; AND purchase_date &lt;= &#39;2021-04-30&#39;

SELECT DISTINCT store)

I am still starting in SQL and I can't seem to move from here.

答案1

得分: 1

以下是翻译好的部分:

假设“most purchases”表示最高销售额而不是销售次数,且“purchase_date”不是文本而是日期类型:

select x.store_id, sum(x.total) total from ( 	
   select p.store_id, (pi.price*pi.quantity) total from purchase_item pi
   left join purchase p 	on pi.purchase_id=p.id 	
   where p.purchase_date between '2021-04-01' AND '2021-04-30' 
) x 
group by x.store_id 
order by total desc 
limit 1; 

如果您只想找到购买次数最多的商店,而不是销售总额:

select p.store_id, count(p.store_id) from purchase p
where p.purchase_date between '2021-04-01' AND '2021-04-30' 
group by p.store_id
order by count(p.store_id) desc limit 1
英文:

Assuming that most purchases means highest sales and not the number of sales and purchase_date is not text but of type date:

select x.store_id, sum(x.total) total from ( 	
   select p.store_id, (pi.price*pi.quantity) total from purchase_item pi
   left join purchase p 	on pi.purchase_id=p.id 	
   where p.purchase_date between &#39;2021-04-01&#39; AND &#39;2021-04-30&#39; 
) x 
group by x.store_id 
order by total desc 
limit 1; 

If you want to just find store with maximum number of purchases and not the Total value of sales:

select p.store_id, count(p.store_id) from purchase p
where p.purchase_date between &#39;2021-04-01&#39; AND &#39;2021-04-30&#39; 
group by p.store_id
order by count(p.store_id) desc limit 1

答案2

得分: 0

select count(store_id) as counted_store,store_id from purchase where MONTH(purchase_date) = '5' GROUP BY counted_store ORDER BY counted_store DESC limit 1

英文:

you can try this

select count(store_id) as counted_store,store_id from purchase where MONTH(purchase_date) = &#39;5&#39; GROUP BY counted_store ORDER BY counted_store DESC limit 1

huangapple
  • 本文由 发表于 2023年5月15日 14:02:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定