Get the Max value of each group in SQL

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
chokkaStudentAsked:
Who is Participating?
 
awking00Connect With a Mentor 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;
0
 
Jared_SCommented:
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]
0
 
chokkaStudentAuthor Commented:
I need Max FileCount, Group by FileName
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
chokkaStudentAuthor 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
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
0
 
Steve WalesSenior Database AdministratorCommented:
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]
0
 
chokkaStudentAuthor 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)
0
 
Jared_SCommented:
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.
0
 
Steve WalesSenior Database AdministratorCommented:
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 ?
0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
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.
0
 
chokkaStudentAuthor 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 !!
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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

0
 
awking00Commented:
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.
0
 
chokkaStudentAuthor 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)
0
 
Jared_SCommented:
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'
0
 
chokkaStudentAuthor 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
0
 
Jared_SConnect With a Mentor 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

0
 
awking00Commented:
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.
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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" ...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.