[英]SQL: HAVING on conditional SUM
我建立了一個查詢,以將公司的銷售統計數據與其他公司進行比較。
簡化后,就像:
SELECT SUM(CASE WHEN company=foobar THEN sales ELSE 0) as sales_foobar,
SUM(sales) as sales_total, country, year, product FROM sales_table
GROUP BY country, year, product HAVING (the above sum again) > 0
遵從性規則要求僅顯示公司有任何銷售的行,而我的代碼將丟棄foobar沒有銷售的行,但由於訂單和退款相等,它也會丟棄銷售為0的行。
現在,我如何才能只獲得公司擁有銷售數據的行?
您可以在HAVING
子句中計算與公司匹配的行數:
SELECT SUM(CASE WHEN company = foobar THEN sales ELSE 0 END) as sales_foobar,
SUM(sales) as sales_total, country, year, product
FROM sales_table
GROUP BY country, year, product
HAVING SUM( company = foobar ) > 0; -- there is at least one record for the company
您應該使用Where:
SELECT SUM(CASE WHEN company=foobar THEN sales ELSE 0) as sales_foobar,
SUM(sales) as sales_total, country, year, product
FROM sales_table
Where sales > 0
GROUP BY country, year, product HAVING (the above sum again) > 0
假設公司='foobar,根據您的問題進行計算即可; 您幾乎只在代碼中完成了答案。 因此,如果您需要除此以外的任何其他特定條件,請告訴我。 我會編輯答案。
SELECT
SUM (CASE WHEN company='foobar' THEN sales ELSE 0 end) as sales_foobar,
SUM(sales) as sales_total,
country,
year,
product
FROM sales_table
GROUP BY country, year, product
HAVING SUM (CASE WHEN company='foobar' THEN sales ELSE 0 end) > 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.