Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1027
  • Last Modified:

How to rewrite Case statement in Group By

Sql server handles this OK (Northwind example), but I'm passing this to another database system that does not allow it in Group By clauses.

How could this be rewritten without the select case in the Group By?

Thx


SELECT
  CASE WHEN c.CompanyName Like 'a%' THEN 'Begins with A' ELSE c.CompanyName END
FROM Customers c
  GROUP BY
  CASE WHEN c.CompanyName Like 'a%' THEN 'Begins with A' ELSE c.CompanyName END
  ORDER BY
  CASE WHEN c.CompanyName Like 'a%' THEN 'Begins with A' ELSE c.CompanyName END
0
TZych
Asked:
TZych
1 Solution
 
g_johnsonCommented:
try assigning an alias to the Case ... End column and grouping by that
doesn't work in MS SQL but may on other database

SELECT
   CASE WHEN blah blah THEN whatever ELSE sometingelse END [A]
   GROUP BY A <--- DOESN'T WORK IN MSSQL, don't know why!
   ORDER BY A  <--- WORKS IN MSSQL
0
 
TZychAuthor Commented:
thanks. good idea..but it didn't work
0
 
J2811Commented:
Well when all things fails, do this

SELECT GIVEMEANAME
FROM (
SELECT
  CASE WHEN c.CompanyName Like 'a%' THEN 'Begins with A' ELSE c.CompanyName END GIVEMEANAME
FROM Customers c ) A
GROUP BY GIVEMEANAME
ORDER BY GIVEMEANAME
;

0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now