Reputation: 13610
Im trying to get statistics for each day with PL/SQL.
Each day have several entries, bukkets of errors :-) I want to group them by day.
What Im currently doing:
SELECT TO_CHAR(dateTime, 'DD') DAY, TO_CHAR(dateTime, 'MM') MONTH, errormessage
FROM log
WHERE (...)
GROUP BY MONTH, DAY, errormessage
This results in ORA-00904: "DAY": invalid identifier (stops on the group by).
Any help? :D
Upvotes: 9
Views: 25848
Reputation: 220877
Your problem is a scope problem. The GROUP BY
clause is part of the statement's table expression and is thus evaluated before the SELECT
clause, i.e. the projection. This means that your projected aliases are not available at grouping time. This is one solution
SELECT DAY, MONTH, errormessage
FROM (
SELECT TO_CHAR(dateTime, 'DD') DAY, TO_CHAR(dateTime, 'MM') MONTH, errormessage
FROM log
WHERE (...)
)
GROUP BY MONTH, DAY, errormessage
this is another:
SELECT TO_CHAR(dateTime, 'DD') DAY, TO_CHAR(dateTime, 'MM') MONTH, errormessage
FROM log
WHERE (...)
GROUP BY TO_CHAR(dateTime, 'MM'), TO_CHAR(dateTime, 'DD'), errormessage
Note that some databases (including MySQL, PostgreSQL, and others) do allow to reference column aliases from the projection in the GROUP BY
clause. In stricter SQL dialects (such as Oracle) that should not be possible, though
Upvotes: 5
Reputation: 12562
SELECT TO_CHAR(dateTime, 'DD') DAY, TO_CHAR(dateTime, 'MM') MONTH, errormessage
FROM log
WHERE (...)
GROUP BY TO_CHAR(dateTime, 'DD'), TO_CHAR(dateTime, 'MM'), errormessage
Column aliases are no good for GROUP BY
, you need the full expression.
Upvotes: 20
Reputation: 60493
SELECT TO_CHAR(dateTime, 'DD') DAY, TO_CHAR(dateTime, 'MM') MONTH, errormessage
FROM log
WHERE (...)
GROUP by TO_CHAR(dateTime, 'DD'), TO_CHAR(dateTime, 'MM'), errormessage
you can't use aliases in group by
Upvotes: 2