SQL需要分组,但我不知道它是如何应用的

时间:2016-03-06 20:23:32

标签: sql sql-server group-by

我多次尝试都没有成功。

问题是

  1. 列出2014年已下达2个或更多订单的安大略省客户的客户ID
  2. 我的回答是

    SELECT Customer.CustId 
    FROM Customer 
       INNER JOIN Orders ON Customer.CustId = Orders.CustId 
    WHERE (Prov = 'ON' AND YEAR( Orders.OrderDate) = '2014') 
    HAVING COUNT (Orders.CustId) > 2;
    

    但是我一直收到一个错误,因为没有group by子句,但我不知道答案会在哪里发挥。

    附件是物理架构

    http://imgur.com/hbosBDM

3 个答案:

答案 0 :(得分:0)

HAVING仅与GROUP BY一起使用。只需包含COUNT(...)> 2作为WHERE子句的一部分。所以你的查询看起来像是:

SELECT Customer.CustId 
FROM Customer 
   INNER JOIN Orders ON Customer.CustId = Orders.CustId 
WHERE (Prov = 'ON' AND YEAR( Orders.OrderDate) = '2014') AND COUNT (Orders.CustId) > 2;

答案 1 :(得分:0)

错误有意义,因为HAVING子句仅在分组(GROUP BY)时应用。应该起作用的查询版本如下:

SELECT Customer.CustId, COUNT(1) Cnt
FROM Customer C
   INNER JOIN Orders O ON C.CustId = O.CustId 
GROUP BY C.CustId
WHERE Prov = 'ON' AND YEAR(Orders.OrderDate) = 2014 
HAVING COUNT (1) > 2;

为了优化一点,您应该避免条件中的标量函数,因为该列上的任何索引都不能使用:

SELECT Customer.CustId, COUNT(1) Cnt
FROM Customer C
   INNER JOIN Orders O ON C.CustId = O.CustId 
GROUP BY C.CustId
WHERE Prov = 'ON' AND (Orders.OrderDate BETWEEN '20140101' AND '20141231') 
HAVING COUNT(1) > 2;

答案 2 :(得分:0)

SELECT Customer.CustId 
FROM Customer 
   INNER JOIN Orders ON Customer.CustId = Orders.CustId 
WHERE (Prov = 'ON' AND YEAR(Orders.OrderDate) = 2014) 
GROUP BY Customer.CustId   --<-- you need to add this group by here 
HAVING COUNT (Orders.CustId) > 2;