-3

此语句返回 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吗?

更新

亚伦和弗莱姆要求了解更多信息:

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 表中具有最重要字段的示例数据可能是:

在此处输入图像描述

测试步骤显示历史测试步骤。从上图中您可以看到 TeststepId = 4 存在 2 次。历史版本(58 秒)和当前版本(59 秒)。

我只想在“当前”视图中显示 59 秒的 teststepid 4。

更新 2

我只想在 59 秒内获得 teststepid 4 并且所有其他 teststepId 都s with their current date. If there are only rows with different teststepid采用这些,因为它们是当前行。

我正要更改我的集成测试并找到解决方案。

4

4 回答 4

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;
于 2012-07-18T12:55:23.163 回答
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
于 2012-07-18T12:58:42.357 回答
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]
于 2012-07-18T12:55:36.690 回答
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)
于 2012-07-18T12:58:55.327 回答