创建sql查询以在时间范围内获取重复列值

时间:2015-04-22 19:44:25

标签: sql-server sql-server-2008

有人可以帮我解决这个问题吗?我希望得到所有customer_id的结果,这些结果在24小时内不止一次重复

SELECT 
    O.Order_No, O.Customer_ID, O.DateOrdered, O.IPAddress,
    C.FirstName, C.LastName, CD.nameoncard
FROM 
    Order_No O
INNER JOIN 
    CardData CD ON O.card_id = CD.id
INNER JOIN 
    Customers C ON O.customer_id = C.customer_id   
ORDER BY
    O.order_no desc   

添加更多细节.. 因此,假设客户ID为xx的订单已于04/23 2:30 pm下单,并且第二个订单在同一天04/23下午5:30以相同的客户ID xx放置。

我希望查询返回给我客户ID xx

由于

2 个答案:

答案 0 :(得分:2)

4. chmod 755 public

要获得在第一个之后发出订单的客户,您可以使用以下查询:

select Customer_ID, CAST(DateOrdered as Date) DateOrdered, count(*) QTDE
from Order_No
group by Customer_ID, CAST(DateOrdered as Date)
having count(*) > 1

SQL Fiddle

让所有客户在任何时间内发出超过一个订单的期限少于或等于24小时

select distinct A.Customer_ID
from Order_No A
inner join (select Customer_ID, min(DateOrdered) DateOrdered from Order_No group by Customer_ID ) B
  on A.Customer_ID = B.Customer_ID
  and A.DateOrdered - B.DateOrdered <= 1
  and A.DateOrdered > B.DateOrdered

SQL Fiddle

答案 1 :(得分:0)

自加入:

SELECT distinct O.Customer_ID
FROM 
Order_No O
inner join Order_No o2
on o.customerID = o2.customerID 
    and datediff(hour, o.DateOrdered, o2.DateOrdered) between 0 and 24
and o.Order_No <> o2.Order_No

这将返回在任何24小时内曾放置过多个订单的所有customer_ID。

编辑添加匹配记录不应该是同一记录的连接条件。应该返回同时下两个不同订单的客户,而不是只下一个订单的客户。