此语句返回2行:
SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt
FROM Teststep ts
INNER JOIN Unit u ON ts.UnitId = u.UnitId
Where u.TemplateId = 2
Group by TeststepId, ts.UnitId
如何获得日期最长CreatedAt
的一行?我应该区分unitId
吗?
更新
Aaron和flem aksed获取更多信息:
1 Template has N Units
1 Unit has N Teststeps
Teststep表的聚簇主键是TeststepId和CreatedAt。
[TeststepId] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[PreCondition] [nvarchar](500) NOT NULL,
[TestInstruction] [nvarchar](500) NOT NULL,
[ExpectedResult] [nvarchar](500) NOT NULL,
[CreatedAt] [datetime] NOT NULL,
[CreatedBy] [nvarchar](50) NOT NULL,
[UnitId] [int] NOT NULL,
Teststep 表
Teststep表中包含最重要字段的示例数据可能是:
测试步骤显示历史测试步骤。从上图中可以看出TeststepId = 4存在2次。历史版本(58秒)和当前版本(59秒)。
我想在59秒内只获得teststepid 4以在“当前”视图中显示。
更新2
我想只用59秒AND得到teststepid 4
所有其他teststepId s with their current date. If there are only rows with different teststepid
取这些因为它们是当前行。
我即将改变我的集成测试并找到解决方案。
答案 0 :(得分:2)
SELECT TOP (1) ts.UnitId, ts.TeststepId, ts.CreatedAt
FROM dbo.Teststep AS ts
INNER JOIN Unit AS u
ON ts.UnitId = u.UnitId
WHERE u.TemplateId = 2
ORDER BY ts.CreatedAt DESC;
如果你想要每个UnitId和SQL Server 2005+一行,那么:
;WITH x AS
(
SELECT ts.UnitId, ts.TestStepId, ts.CreatedAt,
rn = ROW_NUMBER() OVER (PARTITION BY ts.UnitId ORDER BY ts.CreatedAt DESC)
FROM dbo.Teststep AS ts
INNER JOIN Unit AS u
ON ts.UnitId = u.UnitId
WHERE u.TemplateId = 2
)
SELECT UnitId, TestStepId, CreatedAt
FROM x
WHERE rn = 1;
答案 1 :(得分:1)
另一种选择
试试这个:
WITH Data AS
(
SELECT ts.UnitId, ts.TeststepId, ROW_NUMBER() OVER(PARTITION BY UnitId ORDER BY ts.CreatedAt DESC) Position
FROM Teststep ts INNER JOIN Unit u ON ts.UnitId = u.UnitId
WHERE u.TemplateId = 2
)
SELECT *
FROM Data
WHERE Position = 1
答案 2 :(得分:0)
SELECT TOP 1 x.* FROM
(SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt FROM Teststep ts
INNER JOIN Unit u ON ts.UnitId = u.UnitId
Where u.TemplateId = 2
Group by TeststepId, ts.UnitId
ORDER BY ts.CreatedAt DESC) as [x]
答案 3 :(得分:0)
with cte as (
SELECT ts.UnitId,ts.TeststepId, MAX(ts.CreatedAt)as CreatedAt
FROM Teststep ts
INNER JOIN Unit u ON ts.UnitId = u.UnitId
Where u.TemplateId = 2
Group by TeststepId, ts.UnitId)
select ts.UnitId,ts.TeststepId, CreatedAt from cte where CreatedAt
=(select MAX(CreatedAt) from cte)