2015-05-05 121 views
0

我目前在sql studio 2012中工作。我有一个列DateOrdered,ItemNumeber和requestor的表。我正在尝试编写一个select语句,它将提取在7天内已排序两次的项目编号列表。产品编号可以是不同的人或同一个人。在日期范围内选择两次项目号码,sql

+1

你是指在任何* 7天内?或者只是在特定的7天内? –

+0

@CharlesBretana任何7天期限 – Cheddar

回答

1

如果您的意思是在任何7天的期限内,那么这相当于“在另一个订单的7天内订购的项目编号列表”,对吗?

如果是这样,那么

 Select distinct ItemNumber 
    From table t 
    Where exists 
      (Select * From table 
      where itemNumber = t.ItemNumber 
      and DateOrdered > t.DateOrdered 
      and DateOrdered < t.DateOrdered + 7) 
+0

这并没有解决关于被订购两次的部分。 –

+1

是的,它的确如此。如果在7天内存在同一项目的另一条记录,则该另一条记录代表第二个订单, –

+0

这几乎可以工作,但不会捕获重复的零件编号。你能帮助丹吗? – Cheddar

1

having子句是你FREIND。

select someFields, count(*) records 
from someTables 
where some conditions are met 
group by someFields 
having count(*) = 2 
+0

这会带回我的物品编号,但有没有办法我可以看到它们的订购日期。而不是有一个计数,只需制作一个清单,其中的订单日期旁边的商品编号重复列表。 – Cheddar

+0

我明白了,这个解决方案最适合我的问题。谢谢! – Cheddar

0

编辑:修改后的评论。

select * from table a 
inner join table b 
    on a.itemnumber = b.itemnumber 
    and Abs(datediff(DD, a.dateordered, b.dateordered)) <= 7 
    and a.ID < b.ID --or something like this to ensure you don't return matches that are actually the same row. If you don't have an ID and the date ordered is unique for each order, replace ID with that 

如果您需要两个订单/日期在一起,这将成对返回订单。如果你只是想要一个列表,使用:

select distinct a.itemnumber from table a 
inner join table b 
    on a.itemnumber = b.itemnumber 
    and Abs(datediff(DD, a.dateordered, b.dateordered)) <= 7 
    and a.ID <> b.ID --or something like this to ensure you don't return matches that are actually the same row. If you don't have an ID and the date ordered is unique for each order, replace ID with that 

注意,这将返回任何责令至少两次 - 如果你只需要订购的东西究竟两次,你将需要一个不同的查询。

+0

我也有一个数量栏,我没有提到。看起来您的底部查询正在复制该数量。数量列是一个int。 – Cheddar

+0

@达达重复你的意思是什么? “select distinct”应该消除任何重复。您是如何修改查询以合并您的数量列的? – APH