我有这个:
我无法弄清楚如何根据DomainId
和最高日期获取行。
我想获得3行,每个唯一的domainId一行,它必须是domainId
的最高日期
我的许多尝试之一:
SELECT DISTINCT
DomainId, DomainName,
Max([Date]), ServerOnline, DatabaseOnline, ServerPerformance,
DatabasePerformance, SoldTickets
FROM
DomainDetailDataHistory
GROUP BY
DomainId, DomainName, ServerOnline, DatabaseOnline,
ServerPerformance, DatabasePerformance, SoldTickets
我该怎么做?
答案 0 :(得分:2)
您有双标记 - 这适用于SQL Server:
SELECT *
FROM ( SELECT DomainId, DomainName, [Date], serverOnline, DatabaseOnline,
ServerPerformance, DatabasePerformance, SoldTickets,
ROW_NUMBER() OVER (PARTITION BY DomainId ORDER BY date DESC) AS rn
FROM DomainDetailDataHistory
) AS tt
WHERE tt.rn = 1
答案 1 :(得分:1)
现在,您在GROUP BY
语句的输出表中包含了所有内容,因此它将为相应列中每个唯一值组合返回一个新行。
首先尝试将DomainId
和MAX([Date])
关联到临时表中,然后INNER JOIN
DomainId
和[Date]
上的表格。{/ p>
尝试以下方法:
DECLARE @Latest TABLE
(
DomainId bigint,
[date] datetime2
)
INSERT INTO @Latest (DomainId, date)
SELECT DomainId, MAX(Date)
FROm DomainDetailDataHistory
GROUP BY DomainId
SELECT DISTINCT H.DomainId, DomainName,H.[Date],ServerOnline,DatabaseOnline, ServerPerformance, DatabasePerformance, SoldTickets
FROM DomainDetailDataHistory H
INNER JOIN @Latest T ON T.DomainId = H.DomainId AND T.[Date] = H.[Date]
答案 2 :(得分:1)
这也可以,但仅当您使用 SQL Server 2012 + 时。
;WITH DomainDetailHistoryMax AS
(
SELECT
DomainId, DomainName, [Date], serverOnline, DatabaseOnline,
ServerPerformance, DatabasePerformance, SoldTickets
,LEAD([Date]) OVER (PARTITION BY DomainID ORDER BY [Date] ASC) AS cnt
)
SELECT
DomainId, DomainName, [Date], serverOnline, DatabaseOnline,
ServerPerformance, DatabasePerformance, SoldTickets
FROM DomainDetailHistoryMax
WHERE cnt IS NULL;