忽略SQL Server中的HAWING子句

时间:2011-12-21 21:58:37

标签: sql-server

我有一个PURCHASES表,其唯一ID为PURCHASE_ID。我想分解每年有多少不同的客户购买,至少有2次独特购买。这是我写的查询:

SELECT 
  YEAR(PURCHASE_TIME) PURCHASE_YEAR,
  COUNT(DISTINCT CUSTOMER_ID) TOTAL_CUSTOMERS
FROM PURCHASES
GROUP BY YEAR(PURCHASE_TIME)
HAVING COUNT(PURCHASE_ID) > 1

然而,无论购买多少次,这个问题都给了我每年购买的不同患者总数。这意味着,我得到的客户一年只有1次购买,而且有多次购买。就好像忽略了HAVING子句一样 如果我使用HAVING COUNT(DISTINCT PURCHASE_ID) > 1,它也不会改变任何东西。即使我在技术上不需要,因为PURCHASE_ID已经是唯一的并且是主键。

虽然有效。

SELECT 
  PURCHASE_YEAR,
  COUNT(DISTINCT CUSTOMER_ID) TOTAL_CUSTOMERS
FROM
(
  SELECT 
    YEAR(PURCHASE_TIME) PURCHASE_YEAR, 
    CUSTOMER_ID
  FROM PURCHASES
  GROUP BY YEAR(PURCHASE_TIME),CUSTOMER_ID
  HAVING COUNT(PURCHASE_ID) > 1
) VW
GROUP BY PURCHASE_YEAR

3 个答案:

答案 0 :(得分:1)

试试这个:

    SELECT PURCHASE_YEAR,
    COUNT(1) AS CNT
    FROM 
        (SELECT YEAR(PURCHASE_TIME) PURCHASE_YEAR,
        CUSTOMER_ID
        FROM PURCHASES 
        GROUP BY YEAR(PURCHASE_TIME), 
                 CUSTOMER_ID
        HAVING COUNT(1) > 1) AS CNT
    GROUP BY PURCHASE_YEAR
    ORDER BY PURCHASE_YEAR

答案 1 :(得分:0)

尝试以下方法:

SELECT 
  YEAR(PURCHASE_TIME) PURCHASE_YEAR,
  COUNT(CUSTOMER_ID) TOTAL_CUSTOMERS
FROM PURCHASES
GROUP BY YEAR(PURCHASE_TIME), CUSTOMER_ID
HAVING COUNT(PURCHASE_ID) > 1

答案 2 :(得分:0)

尝试将DISTINCT添加到您的过滤器中:

SELECT 
  YEAR(PURCHASE_TIME) PURCHASE_YEAR,
  COUNT(DISTINCT CUSTOMER_ID) TOTAL_CUSTOMERS
FROM PURCHASES
GROUP BY YEAR(PURCHASE_TIME)
HAVING COUNT(DISTINCT PURCHASE_ID) > 1