Finding the highest monthly active users per calendar month in a database where the MONTH column is aggregated such that each month is aggregated to just one row
SELECT
MONTH([OrderDate]) AS Month,
[Name] AS Country,
COUNT([CustomerID]) AS 'Number of Customers Per Month'
FROM
[Sales].[SalesOrderHeader] AS A
LEFT JOIN
[Sales].[SalesOrderDetail] AS B ON A.SalesOrderID = B.SalesOrderID
LEFT JOIN
[Sales].[SalesTerritory] AS C ON A.TerritoryID = C.TerritoryID
GROUP BY
MONTH([OrderDate]), [Name]
ORDER BY
3 DESC
The simplest method uses TOP (1) WITH TIES
and ROW_NUMBER()
in the ORDER BY
:
SELECT TOP (1) WITH TIES MONTH([OrderDate]) AS Month, [Name] AS Country,
COUNT(*) AS [Number of Customers Per Month]
FROM [Sales].[SalesOrderHeader] soh LEFT JOIN
[Sales].[SalesOrderDetail] sod
ON soh.SalesOrderID = sod.SalesOrderID LEFT JOIN
[Sales].[SalesTerritory] st
ON soh.TerritoryID = st.TerritoryID
GROUP BY MONTH([OrderDate]), [Name]
ORDER BY ROW_NUMBER() OVER (PARTITION BY MONTH([OrderDate]) ORDER BY COUNT(*) DESC);
Notes:
a
/ b
/ c
are arbitrary. Use table abbreviations!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.