根据条件从组中选择

时间:2019-09-04 08:49:25

标签: sql sql-server

我有一个结果集ClusterTests:

+--------+---------+------------+-------------+
| TestId | Cluster | TestDate   | TestResult  |
+--------+---------+------------+-------------+
|      1 | A       | 2019-01-01 | Accepted    |
|      2 | A       | 2019-01-15 | Rejected    |
|      3 | B       | 2019-01-01 | Accepted    |
|      4 | B       | 2019-01-15 | Accepted    |
+--------+---------+------------+-------------+

' 我想为每个月和每个群集选择接受的最新测试。对于上述结果集,期望的结果将是:

+---------+---------+------------+
| Cluster | Month   | TestId     |
+---------+---------+------------+
| A       | 2019-01 | 1          |
| B       | 2019-01 | 4          |
+---------+---------+------------+

到目前为止,我所拥有的是:

select Cluster,
       CONVERT(NVARCHAR(7), TestDate, 120) as Month,
       Max(TestId) as TestId
from ClusterTests
group by CONVERT(NVARCHAR(7), TestDate, 120),
         Cluster

但是,这只会检索每个月的最新测试:

+---------+---------+------------+
| Cluster | Month   | TestId     |
+---------+---------+------------+
| A       | 2019-01 | 2          |
| B       | 2019-01 | 4          |
+---------+---------+------------+

任何朝着正确方向的帮助都将受到赞赏!

3 个答案:

答案 0 :(得分:1)

使用此:

SELECT      *
FROM        (
                SELECT      TestId,Cluster,CONVERT(NVARCHAR(7), TestDate, 120) as Month,ROW_NUMBER() OVER(Partition By Cluster,CONVERT(NVARCHAR(7), TestDate, 120) Order By TestDate Desc) as RowNo
                FROM        ClusterTests
                WHERE       TestResult  = 'Accepted'
            ) result
WHERE       result.RowNo = 1

答案 1 :(得分:0)

我认为子查询上的一个简单的where过滤器可以完成这项工作。由于在您的查询中,您还获得了rejected的记录,而您只需要过滤accepted的记录。

select Cluster,
       CONVERT(NVARCHAR(7), TestDate, 120) as Month,
       Max(TestId) as TestId
from (select TestId ,Cluster ,TestDate ,TestResult  from ClusterTests 
      where TestResult = 'Accepted') as tab 
group by CONVERT(NVARCHAR(7), TestDate, 120),
         Cluster

答案 2 :(得分:0)

具有CTE并且不存在:

with cte as (
  select cluster, CONVERT(NVARCHAR(7), TestDate, 120) Month, testid 
  from ClusterTests 
  where testresult = 'Accepted'
)
select c.* from cte c
where not exists (
  select 1 from cte
  where cluster = c.cluster and testid > c.testid and month = c.month
)

请参见demo
结果:

> cluster | Month   | testid
> :------ | :------ | -----:
> A       | 2019-01 |      1
> B       | 2019-01 |      4