SharpDeveloper
Using DISTINCT in Aggregate Functions
By Ashiq Alibhai
Note: This article applies to T-SQL; it may or may not work on other varients of SQL.
Many of us are familiar with T-SQL aggregate functions–COUNT, SUM, AVG, MIN, and MAX. However, one often-neglected feature is that you can use these with the DISTINCT keyword.
Imagine you have the following SQL:
CREATE TABLE #TEMP (
VAL INT)
INSERT INTO #TEMP
VALUES (1)
INSERT INTO #TEMP
VALUES (1)
INSERT INTO #TEMP
VALUES (1)
INSERT INTO #TEMP
VALUES (2)
INSERT INTO #TEMP
VALUES (3)
INSERT INTO #TEMP
VALUES (3)
INSERT INTO #TEMP
VALUES (7)
SELECT COUNT(VAL),
COUNT(DISTINCT (VAL))
FROM #TEMP
…will give you the results 7 and 4. Similarly, SUM(DISTINCT(val)) will give you 13 while the non-distinct gives you 18.
Note that while MIN and MAX are also DISTINCTable, doing so doesn’t really add any additional value.
Related Reading:
Other Interesting Posts
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta







