如何编写SQL查询以返回正确的记录

时间:2018-01-29 14:27:26

标签: sql sql-server join

我无法解决此问题,只能检索“已批准”的记录。 ChangedDate为最大值的状态 - 即表单的最新状态是“已批准”'仅

这两个表是表单 FormStatuses ,FormStatuses在1对多关系中保存表单记录的多个状态记录:

CREATE TABLE [dbo].[Forms]
(
[FormId] [int] IDENTITY(1,1) NOT NULL,
[Property1] [bit]  NULL,
[Property2] [varchar](50) NULL,
CONSTRAINT [PK_Forms_FormId] PRIMARY KEY CLUSTERED 
(
[FormId] ASC
)

CREATE TABLE [dbo].[FormStatuses]
(
[FormStatusId] [int] IDENTITY(1,1) NOT NULL,
[FormId] [int] NOT NULL,
[Status] [varchar](50) NULL,
[ChangedDate] [datetime] NOT NULL
CONSTRAINT [PK_FormStatuses_FormStatusId] PRIMARY KEY CLUSTERED 
(
[FormStatusId] ASC
)

FormStatuses的数据样本 - 应仅返回FormId = 5276:

FormId    Status     ChangedDate
5277      PENDING    1/2/2009 12.10.11.022
5277      RETURNED   2/2/2010 10.20.11.022
5277      APPROVED   5/2/2010 10.20.11.022
5277      RETURNED   5/5/2010 10.20.11.022
5277      APPROVED   1/1/2011 13:48.52.043
5277      REJECTED   1/1/2011 13.52.50.011
5276      DRAFT      4/3/2011 15.10.11.022
5276      APPROVED   3/3/2012 14.10.11.022
5275      DRAFT      3/1/2010 13.10.11.022
5275      PENDING    2/2/2011 12.10.11.022

2 个答案:

答案 0 :(得分:0)

使用此查询:

WITH T AS
(
SELECT
      FormId
    , MAX(FormStatusId) AS 'FormStatusId'
 FROM FormStatuses
GROUP BY FormId
)

SELECT 
       F.FormId
     , F.Property1
     , F.Property2
     , FS.Status
     , FS.ChangedDate
  FROM Forms F JOIN T T ON F.FormId = T.FormId
               JOIN FormStatuses FS ON T.FormStatusId = FS.FormStatusId
                                   AND FS.Status = 'Approved'

答案 1 :(得分:0)

试试这个:

SELECT
    Forms.FormID,   
    Forms.Property1,
    Forms.Property2,
    fs1.Status,
    fs1.ChangedDate
FROM
    forms,
    FormStatuses fs1
JOIN
    (SELECT
        MAX(fs2.ChangedDate) AS latest,
        fs2.FormID
    FROM
        FormStatuses fs2
    GROUP BY
        fs2.FormID) as maxstatus
ON
    fs1.ChangedDate = latest AND
    fs1.FormID = maxstatus.FormID
WHERE
    fs1.FormID = Forms.FormID AND
    fs1.Status = "Approved"

这将创建一个具有表单ID和最大状态日期的Join表,用于比较和确定该最大状态日期的状态是否为#34;已批准"。