I need to create an aggregation function to use for summarizing data.
The function basically should return "#" if more than 1 distinct value in column and return the value if only one distinct value in column.
What I tried so far is;
CREATE FUNCTION dbo.my_agg(@mycol NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @result NVARCHAR(MAX);
SELECT @result = CASE
WHEN COUNT(DISTINCT @mycol) = 1 THEN MAX(@mycol)
ELSE '#'
END
RETURN @result;
END;
Then I realized user defined functions cannot be used in aggregation, I need to run this function in my grouped data via group by.
I think the definition should start with CREATE AGGREGATE
but couldn't find how to implement.
Thanks in advance.
1条答案
按热度按时间p8h8hvxi1#
Apart from the comments above, it will not work also because you can't pass the column name this way. If you pass @mycol, let's say, 'column1' - it will not calculate COUNT(DISTINCT column1). Instead it will calculate COUNT(DISTINCT 'column1') and obviously will always give you 1.
It could be worked around with dynamic SQL, but it's not possible in the UDF in this scenario.
What you could possibly try is to prepare all aggregations in advance when building a temp table with your query, and then use one of them in the main query: