我按ClientID和位置将查询分组如下:
SELECT
lph.ClientID
,lph.LocationID
,MAX(c.ClientName) AS ClientName
,MAX(cp.ClientName) AS ClientPartnerName
,MAX(c.BillingContactName) AS BillingContactName
,MAX(c.BillingEmail) AS BillingEmail
FROM [billing].[TEST_LicensePackageHeader] lph
LEFT JOIN [app].[TEST_Client] c
ON lph.ClientID = c.ClientID
LEFT JOIN [billing].[TEST_LicensePackageClientPartner] lpcp
ON lph.PackageID = lpcp.PackageID
LEFT JOIN [app].[TEST_Client] cp --client partner
ON lpcp.ClientPartnerID = cp.ClientID
WHERE lph.LicenseExpirationDate BETWEEN @FilterStartDate AND @FilterEndDate
AND ( ((LEN(@ClientPartnerSearchString) > 0) AND (cp.ClientName LIKE '%' + @ClientPartnerSearchString + '%') )
OR ((LEN(@ClientPartnerSearchString) = 0)) )
GROUP BY lph.ClientID, lph.LocationID
ORDER BY lph.ClientID, lph.LocationID, MAX(lph.LicenseExpirationDate)
我想对MAX(LicenseExpirationDate)DESC进行排序,以便按ClientID分组以MAX(LicenseExpirationDate)DESC的顺序显示。
仅查看这3列,我需要将其分组如下:
| ClientID | LocationID | MAX(LicenseExpirationDate) |
----------------------------------------------------
| 4 | 3 | 01/03/2019 |
| 4 | 7 | 01/17/2020 |
| 1 | 1 | 02/04/2018 |
| 1 | 3 | 07/13/2018 |
| 2 | 8 | 09/22/2015 |
| 2 | 3 | 01/30/2017 |
基本上,我只需要MAX(LicenseExpirationDate)以排序顺序为先,同时将ClientID和LocationID的分组保持在一起。
希望这是有道理的。我不确定如何在SQL Server中执行此操作。谢谢!
答案 0 :(得分:0)
我想你想要
order by max(max(LicenseExpirationDate)) over (partition by clientId) desc,
clientId,
max(LicenseExpirationDate) asc
这将在整个客户端中按最大LicenseExpirationDate
的顺序对客户端进行排序。然后,它在每个客户端中按LicenseExpirationDate
对每一行进行排序。