I’m trying to write a query to pull some info from our database and I need to group it by part of a string. So I did GROUP BY substring(). However it appears that even though the column I am substring()ing is in the SELECT statement, it still fails. I also tried to put the substr() in the select on it’s own and do an “AS x” with it, but that also fails as it is executed after the GROUP BY.
SELECT
M.Cabot_source,
CASE substring(M.Cabot_source,6,1)
WHEN 'C' THEN 'CoregUserNameLC'
WHEN 'P' THEN 'PPC'
WHEN 'O' THEN 'Organic'
WHEN 'S' THEN 'Ad Swap'
WHEN 'I' THEN 'Internal'
ELSE 'Unknown'
END as source_type
FROM members_ M
WHERE M.Cabot_source != ''
GROUP BY substring(M.Cabot_source,6,1)
This is the error it returns to me:
SQL error reported from db Connection:
> (0x3ddbe8) Lyris function: SQLClass::SendToSQLInternal() Lyris error
> description: Command.Open() failed with error code 80040e14 Database
> error information: Error 8120: Column 'members_.Cabot_source' is
> invalid in the select list because it is not contained in either an
> aggregate function or the GROUP BY clause. (source: Microsoft OLE DB
> Provider for SQL Server) SQL Statement: SELECT M.Cabot_source, CASE
> substring(M.Cabot_source,6,1) WHEN 'C' THEN 'CoregUserNameLC' WHEN 'P'
> THEN 'PPC' WHEN 'O' THEN 'Organic' WHEN 'S' THEN 'Ad Swap' WHEN 'I'
> THEN 'Internal' ELSE 'Unknown' END as source_type FROM members_ M
> WHERE M.Cabot_source != '' GROUP BY substring(M.Cabot_source,6,1)
You have to group over the complete case statement.