简体   繁体   中英

I want an SQLquery to find highest MonthlyActiveUsers per month such that each month is aggregated to just ONE row

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:

  • Use meaning table aliases! a / b / c are arbitrary. Use table abbreviations!
  • Qualify all column references. That is USE the table aliases.
  • Only use single quotes for string and date constants. It is best to use column names that do not need to be escaped. But if you must, use the escape character for your database.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM