Sql 如何在单个语句中执行select?
我有一个Sql Server 2005表,其中包含以下数据: IdHearting是主键(标识),idCase是一个可能重复的外键。StartDate和StartTime指定事件的日期和时间-这两个字段都是DateTime类型(无论出于何种原因,它们都是单独的字段)。所有StartDate数据的时间均为12:00:00。所有StartTime数据的日期均为1900年1月1日。IsScheduled和IsOnCalendar是位字段 我的挑战是为每个案件选择最新的(日期/时间)听证会。如果StartDate/StartTime相同(如第1行和第2行中的情况),则应优先选择已启用IsScheduled和/或IsCalendar的行。如果这些列也是相同的,那么返回哪一行并不重要 为了使这更复杂,我必须在单个SELECT语句中完成这一切(因为它必须在视图中),并且必须返回您在下面看到的所有列 我尝试了几种方法,但我的SQL-FU不强。有什么想法吗?使用:Sql 如何在单个语句中执行select?,sql,sql-server,sql-server-2005,tsql,view,Sql,Sql Server,Sql Server 2005,Tsql,View,我有一个Sql Server 2005表,其中包含以下数据: IdHearting是主键(标识),idCase是一个可能重复的外键。StartDate和StartTime指定事件的日期和时间-这两个字段都是DateTime类型(无论出于何种原因,它们都是单独的字段)。所有StartDate数据的时间均为12:00:00。所有StartTime数据的日期均为1900年1月1日。IsScheduled和IsOnCalendar是位字段 我的挑战是为每个案件选择最新的(日期/时间)听证会。如果Sta
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
检查并查看-可能会通过调整行号来调整顺序…与omg小马的答案几乎相同。排号是你的朋友。我不完全确定位字段是否按您所希望的方式处理,但您已经明白了。和以往一样,最好对所选择的字段进行明确说明,但我很懒
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