【问题标题】:SQL Server : order date and orders beforeSQL Server:订单日期和之前的订单
【发布时间】:2017-03-27 03:58:38
【问题描述】:

我有一个简单的Customers (customerID) 表和一个Orders (orderID, orderdate) 表

我需要获取正好两周前下订单的所有客户的列表,以及他们在那周之前收到的所有订单的数量。

SELECT c.id_customer
FROM customer AS c
JOIN order AS o ON o.customerID = c.customerID
WHERE o.delivery_date = DATEADD(Day,-14,GETDATE())

但我直到周才知道如何计算订单数。

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    您可以使用<= 获取行并使用having 子句检查在给定日期是否存在行:

    select c.id_customer, count(*) as order_count
    from customer as c
    join orders as o on o.customerID = c.customerID
    where o.delivery_date <= DATEADD(Day, - 14, GETDATE())
    group by c.id_customer
    having count(case when o.delivery_date = DATEADD(Day, -14, GETDATE()) then 1 end) > 0;
    

    另请注意,我将表名 order 更改为 orders,因为 order 是 SQL 保留关键字,使用关键字作为表/列标识符通常是个坏主意。

    【讨论】:

      【解决方案2】:
      SELECT c.customerID,o.orderID, count(o.delivery_date)
      FROM customer AS c
      JOIN order AS o ON o.customerID = c.customerID
      WHERE o.delivery_date = DATEADD(Day,-14,GETDATE())
      group by c.customerID,o.orderID 
      

      【讨论】:

        【解决方案3】:

        用其他样本数据试试这个,

         Declare @DaysAgo int=14 --para to be pass in proc
            declare @To Datetime=DATEADD(second,-1,cast((DATEADD(Day, - (@DaysAgo-1), cast(GETDATE() as date)) ) as DATETIME))
           declare @From Datetime=cast((DATEADD(Day, - @DaysAgo, cast(GETDATE() as date)) ) as DATETIME)
        
        
            select c.id_customer, count(*) as order_count
            from customer as c
            join orders as o on o.customerID = c.customerID
            where o.delivery_date >= @From AND 
            o.delivery_date <= @To
            group by c.id_customer
        

        【讨论】:

          猜你喜欢
          • 2018-04-13
          • 1970-01-01
          • 2014-10-04
          • 2018-10-01
          • 1970-01-01
          • 2022-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多