AS-keyword&的多列下一行

时间:2011-07-14 12:49:23

标签: sql tsql

我有许多行,其审核存储在一个单独的表中。使用一个选择,我想获得LatestStateLatestDatePreviousStatePreviousDate。老实说,我不知道从哪里开始为此制定T-SQL查询,但我猜我需要在SELECT内部进行两个子查询(pseudo- pseudo - 代码):

SELECT 
   (SELECT [State], [Date] FROM Audits WHERE HighestID) AS ([LatestState], [LatestDate])
   (SELECT [State], [Date] FROM Audits WHERE NextHighestID) AS ([PreviousState], [PreviousDate])
FROM [Data]

这可能吗?谢谢!

编辑我已经通过使用连接解决了这个问题:

SELECT ps1.Rating, ps1.DatePerformed, ps2.Rating AS PreviousRating, ps2.DatePerformed AS PreviousDate
FROM [Data]
LEFT JOIN [Audit] ps1 ON ps1.[ID] = (SELECT MAX(ID) FROM [Audit] WHERE [ProjectID] = p.[ProjectID])
LEFT JOIN [Audit] ps2 ON ps2.[ID] = (SELECT MAX(ID) FROM [Audit] WHERE [ProjectID] = p.[ProjectID] AND ID < ps1.ID)

感谢您的投入!

2 个答案:

答案 0 :(得分:2)

这将为您提供两行信息。第一行是latest,第二行是previous:)。

select top (2) [State], [Date]
from Audits
order by ID desc

如果你想将它们放在一行,你可以试试这个。

;with cte as
(
  select top 2 [State], [Date], row_number() over(order by ID desc) as rn
  from @Audits
)
select C1.State as LatestState,
       C1.Date as LatestDate,
       C2.State as PreviousState,
       C2.Date as PreviousDate
from cte as C1
  cross join cte as C2
where C1.rn = 1 and C2.rn = 2  

答案 1 :(得分:2)

您不能将一组别名分配给一组列,因为SELECT列表中的子查询允许返回不超过一行一列。仍然可以将一个别名列表分配给用作派生表的子查询,即当它在FROM子句中时(在连接的任一侧,如果有的话)。通常它看起来像这样:

…
FROM
  (subquery) table_alias (column_alias, column_alias, …)
…

所以你的解决方案可能是这样的:

SELECT
  latest.[LatestState],
  latest.[LatestDate],
  previous.[PreviousState],
  previous.[PreviousDate]
FROM
  (
    SELECT [State], [Date]
    FROM Audits
    WHERE condition to find the highest ID
  ) AS latest ([LatestState], [LatestDate]),  /* comma join = CROSS JOIN */
  (
    SELECT [State], [Date]
    FROM Audits
    WHERE condition to find the next highest ID
  ) AS previous ([PreviousState], [PreviousDate])

假设每个子选择只返回一行,这几乎可以为您提供所需的内容。

但是,如果您使用的是SQL Server 2005或更高版本,则可以尝试不同的方法:

WITH ranked AS (
  SELECT
    State,
    Date,
    rn = ROW_NUMBER() OVER (ORDER BY ID DESC)
  FROM Audits
)
SELECT
  LatestState   = MAX(CASE rn WHEN 1 THEN State END),
  LatestDate    = MAX(CASE rn WHEN 1 THEN Date  END),
  PreviousState = MAX(CASE rn WHEN 2 THEN State END),
  PreviousDate  = MAX(CASE rn WHEN 2 THEN Date  END)
FROM ranked
WHERE rn BETWEEN 1 AND 2

基本上,此查询使用条件聚合来显示排名最高的State&amp; DateLatest值,排名第二高State&amp; DatePrevious值。

有用的阅读: