Skip to content

Instantly share code, notes, and snippets.

@rootl
Last active March 30, 2016 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rootl/ce98b4e464a8f91229187487decc9f21 to your computer and use it in GitHub Desktop.
Save rootl/ce98b4e464a8f91229187487decc9f21 to your computer and use it in GitHub Desktop.
Query for SQL 2012 : Percentile_DISC function for median; sum, min, max, avg queries grouped by month and year. I will also post a version for sql versions lower than 2012 that cannot use percentile. Notes: 1) "DailyDiff" is a computed column using "PMCounts-AMCounts/2" to obtain the GateCount Daily Difference. 2) DB isn't partitioned so I had t…
SELECT
Year([Date]) GC_Year,
Month([Date]) GC_Month,
DATENAME(month,[Date]) Month_Name,
SUM(DailyDiff) AS GateCounts_MonthlyTotal,
MIN(DailyDiff) AS GateCounts_MIN,
MAX(DailyDiff) AS GateCounts_MAX,
AVG(DailyDiff) AS GateCounts_AVG,
GateCounts_MED=MAX(Median)
FROM
(
SELECT [Date], DailyDiff,
Median=PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY DailyDiff) OVER (PARTITION BY CAST(MONTH([Date]) AS VARCHAR(2)) + CAST(YEAR([Date]) AS VARCHAR(4)))
FROM GateCounts
) a
WHERE [date]>=cast('2015-08-24 00:00:00' as datetime)
AND [date]<cast('2015-12-30 00:00:00' as datetime)
GROUP BY Year([Date]), Month([Date]), DATENAME(month,[Date])
ORDER BY GC_Year DESC, GC_Month DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment