Get the Max value of each group in SQL

chokka
chokka used Ask the Experts™
on
In SQL, How to get the Maximum value of each group.

In my Syntax, I have a column name : FileCount which counts number of records for each FileName.

My output could be like this..

FileName     FileCount

ABC                1
ABC                2
ABC                3
DEF                 1

So, expected results are

FileName     FileCount

ABC                3
DEF                 1

Below is my current syntax ..


With CTE
As
(
select

                        [FileName],
                        [Trade Name],
                        [Invoice Number],
                        [Invoice Date]
                        ,ROW_NUMBER() OVER(PARTITION BY [FileName] ORDER BY [FileName] ASC) AS FileCount
from                  PlacedOrderDetails
where                  CreatedDate >= '12/21/2012'

)
select
                        [FileName],
                        [Trade Name],
                        [Invoice Number],
                        [Invoice Date]
                        
From                  CTE
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012

Commented:
It looks like you're trying to count the file names. You can get there with this:

SELECT [FileName], count(*) as [FileCount]
FROM PlacedOrderDetails
WHERE CreatedDate >= '12/21/2012'
GROUP BY [FileName]
chokkaStudent

Author

Commented:
I need Max FileCount, Group by FileName
chokkaStudent

Author

Commented:
FileName     FileCount

ABC                1
ABC                2
ABC                3
DEF                 1
GHI                 1
GHI                  2

So, expected results are

FileName     FileCount

ABC                3
DEF                 1
GHI                  2
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

Commented:
Steve WalesSenior Database Administrator

Commented:
To find the max value, this should do the trick

SELECT [FileName], Max(FileCount) as [FileCount]
FROM PlacedOrderDetails
WHERE CreatedDate >= '12/21/2012'
GROUP BY [FileName]
chokkaStudent

Author

Commented:
@sjwales

I tried your query in the very first attempt, before posting over here.

I have around 8 - 9 columns

Group by expect all the columns to be mentioned.

On doing so, we don't get the MAX (FileCount)
Top Expert 2012

Commented:
chokka, did you try the code I posted?
It will work without the cte, and should give you the max file count (by way of counting all the files with the same name).

If I've misunderstood your problem, my apologies.
Steve WalesSenior Database Administrator

Commented:
Is FileCount unique for each occurrence of FileName ?  If so this might work:

Select othercol1, othercol2, otherco3, FileName, FileCount
from
(
SELECT [FileName], Max(FileCount) as [FileCount]
FROM PlacedOrderDetails
WHERE CreatedDate >= '12/21/2012'
GROUP BY [FileName] 
) as a
join PlacedOrderDetails b on a.FileName = b.FileName and a.FileCount = b.FileCount

Open in new window


Even if it's not unique you could change

Select othercol1, othercol2, otherco3, FileName, FileCount

to

Select DISTINCT othercol1, othercol2, otherco3, FileName, FileCount

Would that work ?
Qlemo"Batchelor", Developer and EE Topic Advisor
Top Expert 2015

Commented:
You are correct, you have to enumerate any column not part of an aggregate (min, max, sum, avg, count) in GROUP BY.
That makes sense, because the DBMS cannot decide what you want to see as single values if you have not included them in the GROUP BY. You can for example decide to use the minimum of each other column:
select FileName, min([Trade Name]), min([Invoice Number]), min([Invoice Date]), max(FileCount)
from PlacedOrderDetails
where CreatedDate >= '12/21/2012'

Open in new window

or you want to have the record with the highest FileCount for each FileName, and then the CTE would come into play.

So, you will need to define exactly what result you want to get, including the other columns.
chokkaStudent

Author

Commented:
For all the experts for your query suggestion,

Group by is expecting all the columns which i mentioning in the select query.

On providing all the columns in the Group by, i am not able to get the generated value !!
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

Commented:
this will do (as by my article), based on your code:

With CTE
As
(
select

                        [FileName],
                        [Trade Name],
                        [Invoice Number],
                        [Invoice Date]
                        ,ROW_NUMBER() OVER(PARTITION BY [FileName] ORDER BY [Invoice Date] ASC) AS FileCount
,ROW_NUMBER() OVER(PARTITION BY [FileName] ORDER BY [Invoice Date] DESC) AS rn
from                  PlacedOrderDetails
where                  CreatedDate >= '12/21/2012'
)
select
                        [FileName],
                        [Trade Name],
                        [Invoice Number],
                        [Invoice Date]
                        
From                  CTE
WHERE rn = 1

Open in new window

awking00Information Technology Specialist

Commented:
Can you provide some sample data and the expected output? I suspect the solution will utilize a window function such as row_number() as you have shown in your cte expression, but such functions also include count() and max() which might better provide a solution.
chokkaStudent

Author

Commented:
@angelIII
 

select
                        [FileName],
                        [Trade Name],
                        [Invoice Number],
                        [Invoice Date]
                       
From                  CTE


We are missing the FileCount.
I included, but FileCount reflected as FileCount= 1.


We need MAX(FileCount)
Top Expert 2012

Commented:
I don't believe what your trying to do is uncommon or complicated. There seems to be some communication trouble.

Please try this and see if it is any closer to your desired results.

SELECT
[FileName],
[Trade Name],
[Invoice Number],
[Invoice Date],
(SELECT count(*) FROM PlacedOrderDetails O WHERE P.[FileName] = O.[FileName]) as [FileCount]                      
FROM  PlacedOrderDetails P
WHERE  CreatedDate >= '12/21/2012'
chokkaStudent

Author

Commented:
Thank you for helping.

Sounds simple, but it is complicated.

I have attached the spreadsheet with sample data and expected output.

Hope this will help me as well as experts can bring new query logic !!
ExpectedOutput.xls
Top Expert 2012
Commented:
Using your sample data to create a variable table called @temp:

declare @temp as table (FileName varchar(50), [Trade Name] varchar(25), [Invoice Number] varchar(10), [Invoice Date] datetime, FileCount int)
insert into @temp values ('A176998  12-11-2012.csv',	'ENALAPRIL', 	'176998',	'11/01/2012',	1)
insert into @temp values ('A176998  12-11-2012.csv',	'SENNA PLUS',	'176998',	'11/01/2012',	2)
insert into @temp values ('B176999  12-11-2012.csv',	'SENNA PLUS',	'176999',	'11/15/2012',	1)
insert into @temp values ('C5043379 11-29-2012.csv',	'ADVAIR DISKUS',	'5043379',	'12/02/2012',	1)
insert into @temp values ('C5043379 11-29-2012.csv',	'ASMANEX 30INHL',	'5043379',	'12/02/2012',	2)
insert into @temp values ('C504337911-29-2012.csv',	'ATRIPLA',	'5043379',	'12/02/2012',	3)
insert into @temp values ('C5043379 11-29-2012.csv',	'BENICAR',	'5043379',	'12/02/2012',	4)

Open in new window


Either of these queries works:
SELECT
DISTINCT FileName, [Invoice Number], [Invoice Date], 
(SELECT max([FileCount]) FROM @temp b WHERE b.FileName = a.FileName) as FileCount
FROM @temp a

SELECT FileName, [Invoice Number], [Invoice Date], max([FileCount]) as FileCount
FROM @temp
GROUP BY FileName, [Invoice Number], [Invoice Date]

Open in new window


You can substitute your CTE name and it should work.
Unless there is some reason to use a CTE that isn't discussed here, you can accomplish your goal more efficiently without it by just querying the PlacedOrderDetails table directly.

I believe that syntax would be
SELECT
DISTINCT [FileName],
[Trade Name],
[Invoice Number],
[Invoice Date],
(SELECT count(*) FROM PlacedOrderDetails O WHERE P.[FileName] = O.[FileName]) as [FileCount]                       
FROM  PlacedOrderDetails P
WHERE  CreatedDate >= '12/21/2012'

Open in new window

Information Technology Specialist
Commented:
with cte as
(SELECT
 [FileName],
 [Trade Name],
 [Invoice Number],
 [Invoice Date],
 count([FileName]) over (partition by [FileName] order by [FileName]) as [FileCount],
 row_number() over (partition by [FileName], [Invoice Date] order by [Trade Name] desc)as rn
 FROM PlacedOrderDetails)
SELECT
 [FileName],
 [Trade Name],
 [Invoice Number],
 [Invoice Date],
 [FileCount]
from cte
where rn = 1;
awking00Information Technology Specialist

Commented:
I omitted the CreatedDate since your example did not show it and none of the invoice dates were greater than or equal to 12/21/2012, but it can easily be included in the common table expression.
Guy Hengel [angelIII / a3]Billing Engineer
Most Valuable Expert 2014
Top Expert 2009

Commented:
I am sure my code works. inside the CTE, I have 2 functions with ROW_NUMBER(), one with ORDER BY invoicedate ASC, and one with DESC ...
rn = 1 to return the one with FILE_COUNT = "max" ...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial