每个ID

时间:2017-07-07 22:27:21

标签: sql sql-server

我有一个SQL查询,它提供了太多我需要的信息。我当前的查询如下所示:

USE LetterGeneration 

SELECT g.LetterGenerationTemplateRequestId,
      cast(H.CreatedDate as time) as Time, 
      s.StatusKey 

FROM LetterGenerationStatusHistory H

INNER JOIN LetterGenerationStatus S
ON H.LetterGenerationStatusId = s.LetterGenerationStatusId 
INNER JOIN LetterGeneration G
ON g.LetterGenerationId = h.LetterGenerationId

WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId]
                                        FROM [LetterGenerationTemplateRequest]
                                        WHERE CreatedDate >= DATEADD(day,-90, GETDATE()))
AND (s.StatusKey = 'QC1'
OR s.StatusKey = 'Ready')


ORDER BY LetterGenerationTemplateRequestId, h.CreatedDate ASC

结果我看起来像这样:

LetterGenerationTemplateRequestId   Time          StatusKey
1732189                          01:14:24.1700000   QC1
1732189                          10:13:25.4730000   READY
1732190                          01:14:26.6600000   QC1
1732190                          01:14:26.7230000   QC1
1732190                          01:14:26.7970000   QC1
1732190                          01:14:26.8770000   QC1
1732190                          01:14:26.9500000   QC1
1732190                          01:14:27.0370000   QC1
1732190                          01:14:27.1100000   QC1
1732190                          04:29:17.7170000   READY
1732190                          04:29:33.8500000   READY
1732190                          04:29:50.7900000   READY

我想要的是每个请求ID只有1个结果,状态QC1和状态READY。理想情况下,它看起来像这样:

Request ID  Time    Status
1732189 1:14:24 AM  QC1
1732189 10:13:25 AM READY
1732190 1:14:27 AM  QC1
1732190 4:29:18 AM  READY
1732191 1:14:30 AM  QC1
1732191 4:39:28 AM  READY

如何将结果限制为仅显示每个ID的1个状态结果?我已经在这里检查了一些其他问题,并尝试调整它们以适合我的查询,但我对SQL的有限知识使得它非常困难。

1 个答案:

答案 0 :(得分:1)

您可以使用[...] // Print a word when submit the form view.on('post', { action: 'products' }, function(next) { console.log('POST') next() }) // Get all products from db view.on('init'...) // Render view.render('products')

row_number()

SELECT t.* FROM (SELECT g.LetterGenerationTemplateRequestId, cast(H.CreatedDate as time) as Time, s.StatusKey, ROW_NUMBER() OVER (PARTITION BY g.LetterGenerationTemplateRequestId, s.StatusKey ORDER BY H.CreatedDate DESC ) as seqnum FROM LetterGenerationStatusHistory H INNER JOIN LetterGenerationStatus S ON H.LetterGenerationStatusId = s.LetterGenerationStatusId INNER JOIN LetterGeneration G ON g.LetterGenerationId = h.LetterGenerationId WHERE g.LetterGenerationTemplateRequestId IN (SELECT [LetterGenerationTemplateRequestId] FROM [LetterGenerationTemplateRequest] WHERE CreatedDate >= DATEADD(day,-90, GETDATE()) ) AND s.StatusKey IN ('QC1', 'Ready') ) t WHERE seqnum <= 1 ORDER BY LetterGenerationTemplateRequestId, CreatedDate ASC; 语法中的ORDER BY指定您想要的行。在这种情况下,它是最近的一行。

您可以更改&#34; 1&#34;在外部ROW_NUMBER()中,每组获得尽可能多的行数。