[英]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.