2010-08-01 59 views
2

我有一个SQL Server 2005的表以下数据:如何在单个语句中执行选择?

alt text

idHearing是主键(身份证),idCase是可以复制的外键。 StartDate和StartTime指定事件的日期和时间 - 两个字段都是DateTime类型(无论出于何种原因,这些是单独的字段)。所有StartDate数据的时间为12:00:00。所有StartTime数据的日期为1/1/1900。 IsScheduled和IsOnCalendar是位域。

我的挑战是为每个idCase选择最新的(按日期/时间)听力。如果StartDate/StartTime与第1行和第2行相同(如第1行和第2行中所示),则应优先选择启用了IsScheduled和/或IsCalendar的行。如果这些列是相同的,那么返回哪一行并不重要。

为了使这更加复杂,我必须在单个SELECT语句中完成所有操作(因为它必须位于视图中),并且必须返回下面显示的所有列。

我已经尝试了几种方法,但是我的SQL-FU不强。有任何想法吗?

回答

2

差不多一样OMG小马回答。 Row_number是你的朋友。我不完全确定比特场是按照你想要的方式处理的,但你明白了。与往常一样,最好清楚你选择的领域,但我很懒。

create table #table 
(
    idHearing int, 
    idCase int, 
    startDate datetime, 
    starttime datetime, 
    isscheduled bit, 
    isoncalendar bit 
); 
insert into #table values(1,1,'8/2/2010','3:30:00 PM',1,1) 
insert into #table values(2,1,'8/2/2010','3:30:00 PM',1,0) 
insert into #table values(3,2,'8/3/2010','5:30:00 PM',1,1) 
insert into #table values(4,2,'8/4/2010','9:30:00 PM',1,1) 
insert into #table values(5,3,'8/2/2010','3:00:00 PM',1,1) 

select * from 
(
    select 
     row_number() 
      over 
      (partition by idcase order by 
       startdate desc, 
       starttime desc, 
       isscheduled desc, 
       isoncalendar desc 
      ) idCasePosition, 
     * 
    from #table 
) x 
where idCasePosition=1 

drop table #table 
+0

+1:祝贺制作10K :) – 2010-08-01 05:19:10

+0

非常感谢。 – spender 2010-08-02 00:14:11

+0

为了纪念你过关10k的障碍,请接受。 – AngryHacker 2010-08-06 03:25:44

4

用途:

CREATE VIEW vw_summary AS 
WITH example AS (
    SELECT t.idcase, 
      t.startdate, 
      t.startime, 
      t.isscheduled, 
      t.isoncalendar, 
      ROW_NUMBER() OVER (PARTITION BY t.idcase ORDER BY t.startdate DESC, 
                  t.starttime DESC, 
                  t.isscheduled DESC, 
                  t.isoncalendar DESC) AS rank 
     FROM TABLE t) 
SELECT e.* 
    FROM example e 
WHERE e.rank = 1 

检查&看到的 - 可能调整的ORDER BY对ROW_NUMBER ...

+0

打我吧 – spender 2010-08-01 03:20:42