IrishChieftain
IrishChieftain

Reputation: 15253

Group Certain Rows Together in T-SQL Based on Column Value

I have the following query:

select MT.* 
from MyTable MT 
where 0 = 0  
order by ChangeDate, Type, ItemNumber

Which returns the following:

TableID    ChangeDate    Description    ItemNumber    Type
-------    ----------    -----------    ----------    ----
11259      2019-05-20    Item1          1335          MOVE
11260      2019-05-20    Item2          1475          MOVE
11261      2019-05-20    Item3          1782          UPDATE
11262      2019-05-20    Item4          1789          UPDATE
11263      2019-05-20    Item5          1782          MOVE

I'm trying to group together rows with the same ItemNumber (example: 1782) and am having difficulty trying to achieve this with a GROUP BY clause because I can't figure out how to manipulate an associated aggregate method to achieve that. Anyone?

UPDATE

To be more specific I would like rows with the same ItemNumber to be next to each other as follows:

TableID    ChangeDate    Description    ItemNumber    Type
-------    ----------    -----------    ----------    ----
11259      2019-05-20    Item1          1335          MOVE
11260      2019-05-20    Item2          1475          MOVE
11261      2019-05-20    Item3          1782          UPDATE
11263      2019-05-20    Item5          1782          MOVE
11262      2019-05-20    Item4          1789          UPDATE

Upvotes: 0

Views: 90

Answers (1)

GMB
GMB

Reputation: 222482

It looks like you just want a different ORDER BY clause - I don't see how this relates to aggregation (GROUP BY). It looks like it should be:

order by ChangeDate, ItemNumber, TableID

Or, possibly:

order by ItemNumber, ChangeDate, Type

Upvotes: 1

Related Questions