Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to get group by and order by in same query
Posted

You can use the below query

SQL
SELECT
    [ALL | DISTINCT | DISTINCTROW ]
          select_expr [, select_expr ...]
    [FROM table_references
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    ]
 
Share this answer
 
v2
You can use GROUP BY and ORDER BY very easily, but...only if you are ordering by one of the columns in the GROUP:
SQL
SELECT Title FROM MyTable
GROUP BY Title
ORDER BY Title DESC
If the column you want to ORDER BY isn't in the GROUP, then that means it can have multiple values for each row the GROUP BY will return and SQL can't sort based on that - because it doesn't know which of the values it should use for sorting.
 
Share this answer
 
Hi,

I am giving my solution what i think,


SQL>

Select column_name from Table_name
group by column_name
order by column_name1
 
Share this answer
 
Comments
OriginalGriff 8-May-15 3:03am    
Reason for my vote of one: Please check your answers before you post them: that SQL will always give an error:
"Column "Table_name.column_name1" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
sekar305 8-May-15 3:49am    
using sum(column_name) is it possible
OriginalGriff 8-May-15 3:57am    
Yes - because that is an Aggregate query which "collapses" all the possible values for the row to a single row. Same with MAX, MIN, COUNT, AVG ...
sekar305 8-May-15 4:00am    
pls check this query:

select SUM(credit) as credit ,SUM(debit) as debit,short from balancesheet where status='COMPLETED' order by short (select SUM(credit) as credit ,SUM(debit) as debit from balancesheet where status='COMPLETED' group by header_type)
OriginalGriff 8-May-15 4:07am    
Check it for what?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900