【问题标题】:How to perform a select in a single statement?如何在单个语句中执行选择?
【发布时间】:2010-08-01 02:54:05
【问题描述】:

我有一个包含以下数据的 Sql Server 2005 表:

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

我的挑战是为每个 idCase 选择最近的(就日期/时间而言)听证会。如果 StartDate/StartTime 相同(如在第 1 行和第 2 行中),则应优先考虑启用了 IsScheduled 和/或 IsCalendar 的行。如果这些列也相同,那么返回哪一行都没有关系。

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

我尝试了几种方法,但我的 SQL-FU 并不强大。有什么想法吗?

【问题讨论】:

    标签: sql sql-server sql-server-2005 tsql view


    【解决方案1】:

    用途:

    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
    

    检查并查看 - 可能会调整 ROW_NUMBER 上的 ORDER BY...

    【讨论】:

      【解决方案2】:

      和 omg ponies 的回答差不多。 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 2017-07-15
        • 2019-12-30
        • 1970-01-01
        相关资源
        最近更新 更多