这个查询完全适用于MySQL,但我应该重写使用MSSQL,这不起作用
SELECT DISTINCT TOP 20 [UF].[id], [UF].[created], [Company].[name]
FROM [user_functions] AS [UF]
LEFT JOIN [companies] AS [Company] ON ([Company].[code] = [UF].[company_code])
WHERE [UF].[user_id] = 8923 AND [UF].[state] != 500
ORDER BY [UF].[created] DESC
此查询返回重复的行,即使我设置了DISTINCT
。
但是,当从[Company].[name]
移除SELECT
时,它会正确返回
我想使用[Company]
和[UF]
表中的许多字段。
答案 0 :(得分:0)
您可以尝试使用row_number并获取第一个rownum,如下所示:
select * from
(
SELECT DISTINCT TOP 20 [UF].[id], [UF].[created], [Company].[name],
RowNum = row_number() over(partition by [Company].[name] order by [UF].[ID])
FROM [user_functions] AS [UF]
LEFT JOIN [companies] AS [Company] ON ([Company].[code] = [UF].[company_code])
WHERE [UF].[user_id] = 8923 AND [UF].[state] != 500
) a where RowNum = 1
order by a.Created Desc