Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use a new created column in GROUP BY

In my SQL query, I want to check if a column has the string ‘test’ and safe the value in a new column

When I use the new column in GROUP BY, I get error saying it can’t find the new column:

SELECT
    CAST([EvtTime] as date) AS myDay,
    CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END AS testResult,
    COUNT_BIG(*) AS myCount,
    [name]
FROM [mytable]
GROUP BY myDay, testResult

I am using SQL Server.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

CROSS APPLY is a clean way to solve this issue.

SELECT
    CAST([EvtTime] as date) AS myDay,
    X.testResult,
    COUNT_BIG(*) AS myCount,
    [name]
FROM myTable
CROSS APPLY (VALUES (CASE WHEN [result] LIKE '%test%' THEN 1 ELSE 0 END)) AS X(testResult)
GROUP BY myDay, testResult
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading