数据库使用不同的列多次选择相同的记录

时间:2011-05-11 16:39:41

标签: sql database database-design ms-access

我有一个包含多个日期列的订单表(部门完成日期)。我想查询表并为指定日期的每个匹配返回一个唯一的行,并提供对该行被选中的原因的引用。

所以从这张表:

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中,我不确定这是否可以在查询级别进行,或者是否需要子报表生成。

非常感谢你的帮助!

3 个答案:

答案 0 :(得分: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' 

答案 1 :(得分: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'

答案 2 :(得分: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中),当它是别名时,您确实应该避免使用保留字命名列。