[英]SQL Query - Count number of records where SUM is greater than current record
我正在编写一个 SQL 查询,按产品对总销售额求和,我需要一种方法来使用 COUNT function 来计算总和(总销售额)大于当前记录的记录数。
这是我到目前为止所拥有的:
SELECT product_id, SUM(product_gross_revenue) AS TotalSales, t.name as Category
FROM {前缀}wc_order_product_lookup c
左加入 wp_posts p ON p.id = c.product_ID
左连接 wp_term_relationships AS tr ON tr.object_id = p.ID
加入 wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id = tr.term_taxonomy_id
加入 wp_terms AS t ON t.term_id = tt.term_id
哪里(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
我想在我的 select 语句中添加一个 COUNT function 语句,该语句计算 TotalSales 大于当前记录的记录数,但我尝试的一切都失败了。
例如,我当前的表如下所示:
product_id | product_gross_revenue | 姓名 |
---|---|---|
1 | 50 | 猫 A |
2 | 150 | 猫 B |
3 | 100 | 猫 C |
1 | 150 | 猫 A |
3 | 200 | 猫 C |
我希望我想要的 output 是:
product_id | 总销售额 | 姓名 | 数数 |
---|---|---|---|
1 | 200 | 猫 A | 2 |
2 | 150 | 猫 B | 3 |
3 | 300 | 猫 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.