Babu James
Babu James

Reputation: 2843

SQL Group An Already Grouped Result

I have to perform the following on some table:

  1. I need to group it first based on something and then
  2. I need to group the previous result again based on something else.

Is there any way to do both groupings in single query?

Upvotes: 1

Views: 1343

Answers (2)

von v.
von v.

Reputation: 17108

It will be easier for us to help you if you show us some code as "J W" requested. With not much information on the structure of your query, let me give it a shot. Are you trying to do something like this:

WITH    FirstGroup
AS      (            
        SELECT  Color, ReorderPoint, COUNT(*) Items
        FROM    Production.Product
        GROUP   BY Color, ReorderPoint        
        )
SELECT  Color, SUM(ReorderPoint), SUM(Items) TotalItems
FROM    FirstGroup
GROUP   BY Color

NOTE: I used the AdventureWorks database

Upvotes: 1

Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

you should check your wanted results by those two methods:

select *
from (
   select *
   from table
   group by acol
)
group by bcol



select *
from table
group by acol, bcol

try those two, they should help

Upvotes: 1

Related Questions