select如何在WHERE条件下使用HAVING子句的所有数据?

How select all data using HAVING clause in WHERE condition?

我创建了一个 table 来记录每月由谁销售了哪种产品以及销售了多少;

month total product cons_name
2020-01 10 xyz 123
2020-02 5 abc 456
2020-02 4 def 789

我正在根据此 table 创建一个查询,以找出自年初以来谁在某些产品上销售了超过 500 件产品,但在撰写本文时我有点困惑。因为我不需要查询它在一年中的销量,但我需要查询它每个月的销量。通过这个查询,我可以很容易地找到一年内总共超过 500 笔销售:

SELECT cons_name, product, SUM(total)
FROM TMP_REPORT
WHERE product IN ('abc','xyz')
GROUP BY cons_name, product
HAVING sum(total) > 500

但是当涉及到详细查询时,我做到了这一点:

SELECT 
  month,
  product,
  cons_name,
  total
FROM TMP_REPORT 
WHERE product IN ('abc','xyz')
AND cons_name IN 
              (SELECT 
                 cons_name
               FROM TMP_REPORT 
               WHERE 
                 product IN ('abc','xyz') 
               GROUP BY 
                 cons_name 
               HAVING sum(total) > 500)

这个查询的结果显示即使已售出的产品总数也不是 500。例如,我们希望 cons_name 名为 '123' 的查询结果不会出现在仅售出 200 件的情况下 'abc' 产品在一年中,但它确实存在,因为 where 子句。我知道我的错误,但我不知道如何改正。

我该怎么做?

感谢您的帮助。

一种方法使用 SUM 作为解析函数:

WITH cte AS (
    SELECT t.*, SUM(total) OVER (PARTITION BY cons_name, product) sum_total
    FROM TMP_REPORT t
    WHERE product IN ('abc', 'xyz')
)

SELECT *
FROM cte
WHERE sum_total > 500;

我无法清楚地理解您的要求,我假设您需要查询以获取每月销量超过 500 件的产品。我希望下面的查询能够获取您需要的记录。

-- YearlyReportCTE will Qualify the people who sold more than 500 units in total (i.e. yearly from your statement)
WITH YearlyReportCTE AS (

SELECT  
  product,
  cons_name,
  SUM(total) AS Total
FROM #TMP_REPORT
WHERE product in ('abc','xyz')
GROUP BY product,cons_name
HAVING SUM(total) > 500
)--This Query will fetch the month wise report from the qulified records
SELECT  month,
  TR.product,
  TR.cons_name,
  SUM(TR.total) AS Total
FROM #TMP_REPORT TR
JOIN YearlyReportCTE YR ON YR.cons_name = TR.cons_name
AND YR.product = TR.product
GROUP BY month,TR.product,TR.cons_name