[英]SQL Query - Count number of records where SUM is greater than current record
I am writing a SQL query that SUMs the total sales by product, and I need a way to use the COUNT function to count the number of records whose SUM (totalsales) is greater than the current record.我正在编写一个 SQL 查询,按产品对总销售额求和,我需要一种方法来使用 COUNT function 来计算总和(总销售额)大于当前记录的记录数。
Here is what I have so far:这是我到目前为止所拥有的:
SELECT product_id, SUM(product_gross_revenue) AS TotalSales, t.name as Category SELECT product_id, SUM(product_gross_revenue) AS TotalSales, t.name as Category
FROM {prefix}wc_order_product_lookup c FROM {前缀}wc_order_product_lookup c
LEFT JOIN wp_posts p ON p.id = c.product_ID左加入 wp_posts p ON p.id = c.product_ID
LEFT JOIN wp_term_relationships AS tr ON tr.object_id = p.ID左连接 wp_term_relationships AS tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id = tr.term_taxonomy_id加入 wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id = tr.term_taxonomy_id
JOIN wp_terms AS t ON t.term_id = tt.term_id加入 wp_terms AS t ON t.term_id = tt.term_id
WHERE (t.name='Cat A' OR t.name='Cat B' OR t.name='Cat C' OR t.name='Cat D' OR t.name='Cat E')哪里(t.name='Cat A' OR t.name='Cat B' OR t.name='Cat C' OR t.name='Cat D' OR t.name='Cat E')
GROUP BY product_id ORDER BY TotalSales DESC GROUP BY product_id ORDER BY TotalSales DESC
I would like to add a COUNT function to my select statement that counts the number of records where TotalSales is greater than the current record, but everything I've tried has failed.我想在我的 select 语句中添加一个 COUNT function 语句,该语句计算 TotalSales 大于当前记录的记录数,但我尝试的一切都失败了。
Example, my current table looks like this:例如,我当前的表如下所示:
product_id ![]() |
product_gross_revenue ![]() |
name![]() |
---|---|---|
1 ![]() |
50 ![]() |
Cat A![]() |
2 ![]() |
150 ![]() |
Cat B![]() |
3 ![]() |
100 ![]() |
Cat C![]() |
1 ![]() |
150 ![]() |
Cat A![]() |
3 ![]() |
200 ![]() |
Cat C![]() |
What I would like my desired output to be:我希望我想要的 output 是:
product_id ![]() |
TotalSales![]() |
name![]() |
Count![]() |
---|---|---|---|
1 ![]() |
200 ![]() |
Cat A![]() |
2 ![]() |
2 ![]() |
150 ![]() |
Cat B![]() |
3 ![]() |
3 ![]() |
300 ![]() |
Cat C![]() |
1 ![]() |
with data as (<your query minus order by>)
select *,
(
select count(*)
from data d2
where d2.TotalSales > d1.TotalSales
) as X
from data d1
order by TotalSales desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.