Suppose I have a table like so:
ID | Purchases | Quantity | Products |
---|---|---|---|
001 | 5 | 7 | 2 |
002 | 12 | 24 | 9 |
Is there a way in SQL where I can return aggregate information about each column like so:
Column | Min | Max | Avg | Count |
---|---|---|---|---|
Purchases | 5 | 12 | 6.5 | 2 |
Quantity | 7 | 24 | 14.6 | 3 |
Products | 2 | 9 | 3.7 | 4 |
I can define a list of columns I want to return metrics on with DECLARE
DECLARE @METRICS VARCHAR(8000);
SET @METRICS = 'Purchases, Quantity', 'Products';
SELECT @METRICS AS ColumnNames;
But then how to write a SELECT
statement that returns the aggregated results?
I thought I could do something like this based on @ggordon response here https://stackoverflow.com/a/69600079/2430558, but my declared variable is a list
DECLARE @MyQuery NVARCHAR(4000) = CONCAT(N'
SELECT
AVG(', @METRICS, N') AS Col_Avg
FROM mytable GROUP BY', @METRICS);
EXECUTE SP_EXECUTESQL @MyQuery;