2011-05-11 78 views
0

我有一个包含多个日期列(部门完成日期)的订单表。我想查询表格并为指定日期的每个匹配返回一个唯一行,并给出为什么选择该行的参考。数据库多次使用不同列选择相同记录

从该表

所以:

OrderID OrderName Date1  Date2  Date3 
456  feh   5/1/2011 6/1/2011 3/1/2011 
487  meh   12/1/2010 2/1/2011 8/1/2011 

如果查询任意日期比4/1/2011更大我想回:

456  feh   5/1/2011  Date1 
456  feh   6/1/2011  Date2 
487  meh   8/1/2011  Date3 

的数据是在MS Access和我m不知道这是可能的在查询水平或将要求子报表产生。

非常感谢您的帮助!

+0

发表评论在错误的地方。在这里发帖:两个联合声明都有效,但是,我希望最后一列不是该字段中的日期,而是列名或匹配原因。非常感谢!! – 2011-05-11 16:59:34

回答

0

试试这个让你的最后一栏:

Select OrderID, OrderName, Date1 as SelDate, 'Date1' as Reason 
    from table where date1>'4/21/2011' 
UNION ALL 
Select OrderID, OrderName, Date2 as SelDate, 'Date2' as Reason 
    from table where Date2>'4/21/2011' 
UNION ALL 
Select OrderID, OrderName, Date3 as SelDate, 'Date3' as Reason 
    from table where Date3>'4/21/2011' 

另外请注意,我改变了SelDate列的别名 - 甚至尽管它不是关键的(在Access中),但它确实应该避免使用保留字命名列。

+0

那岩石,谢谢!显然,这是整个记录集中的3次点击,对吗? – 2011-05-11 18:43:02

+0

嗯....最有可能的是,尽管它全部由查询引擎(“服务器”,即使它实际上是本地的Access)处理,然后在它返回之前由联合组合。谷歌“Jet showplan”如果你真的想知道细节。 – RolandTumble 2011-05-11 20:52:00

0

这是通过查询实现:

Select OrderID, OrderName, Date1 as Date 
from table where date1>'4/21/2011' 

UNION ALL 

Select OrderID, OrderName, Date2 as Date 
from table where Date2>'4/21/2011' 

UNION ALL 

Select OrderID, OrderName, Date3 as Date 
from table where Date3>'4/21/2011' 
+0

这个和上面的工作,唯一的调整是我希望最后一列不包含日期,而是包含匹配的标题或原因。 – 2011-05-11 16:57:22

+0

您需要为此添加另一列。 – garnertb 2011-05-11 18:09:59

1
Select OrderID, OrderName Date1 as Date, 'Date1' as ComparedDate 
from table where date1>'4/21/2011' 
UNION ALL 
Select OrderID, OrderName Date2 as Date, 'Date2' as ComparedDate 
from table where Date2>'4/21/2011' 
UNION ALL 
Select OrderID, OrderName Date3 as Date, 'Date1' as ComparedDate 
from table where Date3>'4/21/2011'