在不同年份查找重复出现的数据

时间:2013-02-07 21:31:40

标签: sql sql-server-2008

我有一张桌子。在其中我有订单的客户,订单和日期。让我们假装就是这样:

Customer   Orders  Date
----       ----    ----
Smith        1     2012-02-18 11:22:29.000
John         1     2012-08-21 02:04:38.000
Jones        1     2013-01-02 03:23:12.000
Smith        1     2013-02-06 09:12:32.000

我想知道哪些客户在一年多的时间内退回并下了订单以及他们下了多少订单。那么,史密斯在2012年和2013年订购了吗?是。这两年有多少次?两次。

结果如下:

Customer   Orders  
----       ---- 
Smith        2 

我知道如何计算订单在两年内的订购次数,但我不知道如何排除一年内​​订购的人,而不是两者。

SELECT 
    o.Customer, 
    COUNT(o.Orders) as Orders
FROM Order as o
WHERE Date BETWEEN '2012-01-01' AND '2014-01-01'
GROUP BY o.Customer

我首先环顾四周,但我只看到从两个不同的桌子中拉出的答案,我迷路了。 :(

3 个答案:

答案 0 :(得分:1)

使用HAVING子句。

SELECT 
    o.Customer, 
    COUNT(o.Orders) as Orders
FROM Order as o
WHERE Date BETWEEN '2012-01-01' AND '2014-01-01'
GROUP BY o.Customer
HAVING COUNT(o.Orders) > 1

如果您专门寻找不同年份的订单,那么这里是查询

SELECT 
        o.Customer,  
        COUNT(o.Orders) as Orders
    FROM Orders as o
    WHERE Date BETWEEN '01-Jan-2012' AND '01-Jan-2014'
    GROUP BY o.Customer
    HAVING COUNT(DISTINCT YEAR(Date)) > 1

这是SQL Fiddle

答案 1 :(得分:0)

这将检查您是否有不同年份的订单。

SELECT 
    o.Customer, 
    COUNT(*) as Orders
FROM Order as o
WHERE Date BETWEEN '2012-01-01' AND '2014-01-01'
GROUP BY o.Customer
HAVING MIN(YEAR(o.Date)) <> MAX(YEAR(o.Date)) 

如果您的约会日期不是一年。

SqlFiddle,有一些不同的数据,以查看having子句的区别。

提示: 不要将Order用作表名:这是一个保留关键字,会引起混淆。

答案 2 :(得分:0)

这就是我要做的事情:

 WITH A AS (
  SELECT Customer
     ,   Orders
     ,   Date
     ,   [Year] = Year(Date)
  FROM   [Order]
 )
 ,   B AS (
  SELECT Customer
     ,   Orders = SUM(A.Orders)
     ,   [Year]
  FROM   A
  GROUP BY  
         Customer
    ,    A.[Year]
)
,    Orders2012 AS (
  SELECT *
  FROM   B
  WHERE  B.[Year] = 2012
)
,    Orders2013 AS (
   SELECT *
   FROM   B
   WHERE  B.[Year] = 2013
)
SELECT   O12.Customer
     ,   Orders2012 = O12.Orders
     ,   Orders2013   O13.Orders
     ,   TotalOrders = O12.Orders + O13.Orders
FROM    Orders2012 O12
    JOIN Orders2013 O13
        ON O12.Customer = O13.Customer

通过将其分解成一小段处理,我(我希望)在每一步都清楚我正在做什么。我所有的选择都很简单。我的查询很长,但很容易理解,扩展,修改或添加另一年。