【问题标题】:Sub query for two tables base on status using SQL使用 SQL 基于状态的两个表的子查询
【发布时间】:2021-05-06 05:18:04
【问题描述】:

我有两个表 Patient 和 PatientStatusLog 使用 SQL 表

1.病人

sno   patientid   status      createdby   Reegion
 1     481910      D             1222     India
 2     476795      D             1222     India

2.PatientStatusLog

sno     patientid   status           comments       createdby     CreatedDate(dd/mm/yyyy)
1       481910      A                mycommnet       1222         01/01/2000
2       481910      A                mycommnet       1222         02/01/2000      
3       481910      B                mycommnet       1222         01/01/2000
4       481910      C                mycommnet       1222         01/01/2000

我需要像下面这样具有状态 A 和 createddate 的输出应该使用两个表的 Patientid 从 PatientStatusLog 表中最近通过日期

Region    status     CreatedDate
India      A         02/01/2000

【问题讨论】:

    标签: sql sql-server subquery


    【解决方案1】:

    你可以使用窗口函数:

    select . . .    -- whatever columns you want
    from Patient p join
         (select psl.*,
                 rank() over (partition by patientid order by createddate desc) as seqnum
          from PatientStatusLog psl
         ) psl
         on p.patientid = psl.patientid
    where psl.seqnum = 1 and psl.status = 'A';
    

    请注意,这里使用rank(),因为创建日期似乎有重复。

    【讨论】:

      【解决方案2】:

      试试这个:

      SELECT TOP 1
          p.Region,
          psl.Status,
          psl.CreatedDate
      FROM
          Patient [p]
          JOIN PatientStatusLog [psl] ON psl.patientid = p.patientid
              AND psl.status = 'A'
      ORDER BY
          psl.CreatedDate DESC
      

      对于子查询请求:

      SELECT
          p.Region,
          x.status,
          x.CreatedDate
      FROM
      (
          SELECT TOP 1
              PatientId,
              Status,
              CreatedDate
          FROM
              PatientStatusLog
          WHERE
              status = 'A'
          ORDER BY 
              CreatedDate DESC
      ) AS x
          JOIN Patient [p] ON p.PatientId = x.PatientId
      

      请注意,从代码可读性和优化的角度来看,这绝对不是处理此问题的最佳方法。

      【讨论】:

      • 我需要使用子查询我有其他状态要保持在单行中。 @Wellerman
      • 子查询来自什么?听起来你的问题不完整。请添加尽可能多的详细信息(示例数据集、您尝试过的内容、预期输出与您的代码给出的输出、任何错误消息等),以便我给您一个准确的答案。
      • 我们可以使用子查询来实现这一点,第二个表应该是子查询。 @Wellerman
      • @mohdmazharkhan 查看我编辑的答案,如果您想要的话,请告诉我。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      相关资源
      最近更新 更多