2

我有一张桌子。其中我有客户、订单和订单日期。让我们假设它是这样的:

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

我确实先环顾四周,但我只看到从两张不同的桌子上提取的答案,我迷路了。:(

4

3 回答 3

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 小提琴

于 2013-02-07T21:33:20.050 回答
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

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

于 2013-02-07T22:30:09.377 回答
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,有一点不同的数据,看看有子句的区别。

提示:不要使用 Order 作为表名:这是保留关键字,会造成混淆。

于 2013-02-07T21:36:28.287 回答