GROUP BY SQL语句中的Sub SELECT

时间:2015-04-13 21:26:33

标签: sql sql-server greatest-n-per-group

我有一个表,我解析了一大堆VPN日志。该表没有主键字段,guid字段是所有内容的关联方式。我想选择由guid分组的行。并在组中为特定字符串运行子选择。不确定这是否有意义,这是查询:

SELECT [guid]
  ,Max([username]) AS [User]
  ,MIN([datetime]) AS Minimum
  ,Max([datetime]) AS Maximum
  ,DATEDIFF(mi, MIN([datetime]), Max([datetime])) AS "Duration in Minutes"
  ,(SELECT top 1 [data] FROM [Admin].[dbo].[VPNLogs] WHERE [data] LIKE '%The user was active for%') AS "Data"
FROM [Admin].[dbo].[temp_VPNLogs]
GROUP BY [guid]
ORDER BY "Duration in Minutes" DESC

除非数据字段的子选择只是为所有结果返回相同的行,而我希望它根据Group By选择它,否则这很有效。每个VPN连接条目都有4行具有相同的guid,这就是我按照guid进行分组的原因,我想专门为每个组选择具有字符串“用户有效”的数据字段。如果需要进一步澄清,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:1)

相关子查询是您需要的:

SELECT [guid]
  ,Max([username]) AS [User]
  ,MIN([datetime]) AS Minimum
  ,Max([datetime]) AS Maximum
  ,DATEDIFF(mi, MIN([datetime]), Max([datetime])) AS "Duration in Minutes"
  ,(SELECT top 1 [data] FROM [Admin].[dbo].[VPNLogs] V1 WHERE [data] LIKE '%The user was active for%' AND v1.guid = v.guid) AS "Data"
FROM [Admin].[dbo].[temp_VPNLogs] V
GROUP BY [guid]
ORDER BY "Duration in Minutes" DESC