我有一个固有的SQL连接表来给我所需的结果,但返回的数据集(C#)不同,因为它现在重命名列名或以1递增。
SELECT TOP 1 *
FROM [dbo].[ComputerState] as a
INNER JOIN [dbo].[ComputerState] as b ON a.ServiceName != b.ServiceName
WHERE a.State = 5 and b.State = 5
AND a.ServiceName IN (
SELECT [ServiceName] FROM [dbo].[ComputerState]
)
问题是它返回像这样的行,
[ComputerName, ServiceName, ComputerName1, ServiceName1]
[server, service, server2, service2]
我可以像原始表格格式一样返回
[ComputerName, ServiceName]
[server, service]
[Server2, service2]
我当然可以从列名中删除INT 1,但如果我可以避免这种情况会很好。
答案 0 :(得分:0)
您可以选择a.*
代替*
。此外,您可能希望使用WITH TIES
TOP
选项
SELECT TOP 1 WITH TIES a.*
FROM [dbo].[ComputerState] as a
INNER JOIN [dbo].[ComputerState] as b ON a.ServiceName != b.ServiceName
WHERE a.State = 5 and b.State = 5
AND a.ServiceName IN (
SELECT [ServiceName] FROM [dbo].[ComputerState]
)
但是,使用TOP
而不使用ORDER BY
通常是一个坏主意。我不知道你打算查询什么(访问同一桌子三次通常是一个坏主意)。
答案 1 :(得分:0)
在输出中使用UNION,您可以将结果移到彼此之下:
SELECT TOP 1 a.*
FROM [dbo].[ComputerState] as a
INNER JOIN [dbo].[ComputerState] as b ON a.ServiceName != b.ServiceName
WHERE a.State = 5 and b.State = 5
AND a.ServiceName IN (
SELECT [ServiceName] FROM [dbo].[ComputerState]
)
UNION ALL
SELECT TOP 1 b.*
FROM [dbo].[ComputerState] as a
INNER JOIN [dbo].[ComputerState] as b ON a.ServiceName != b.ServiceName
WHERE a.State = 5 and b.State = 5
AND a.ServiceName IN (
SELECT [ServiceName] FROM [dbo].[ComputerState]
)
P.S。说实话,这可能会导致性能提升,因为INNER JOIN
将会完成两次。他们可能是一个更有效的问题,但我不确定如何做得最好。