I wrote this line in mysql and it works
SELECT
IDKartoch,
SUM(SummOpl) AS Total
FROM
Oplata
GROUP BY
IDKartoch
HAVING
SUM( Oplata.SummOpl ) >= 0
ORDER BY
IDKartoch;
And I get this result:
But after I remove the IDKartoch
column from the SELECT
...
SELECT
SUM(SummOpl) AS Total
FROM
Oplata
GROUP BY
Oplata.IDKartoch
HAVING
SUM( Oplata.SummOpl ) >= 0
ORDER BY
Oplata.IDKartoch;
I get this error
Function or column reference to '
IDKartoch
' in theORDER BY
clause its invalid SQLCODE=-854
CodePudding user response:
The syntax
ORDER BY Oplata.IDKartoch
has a fully qualified reference to theOplata
"BASE TABLE
" (as opposed to aVIEW
or derived-table).However, when you use
GROUP BY
in a query your query now represents an anonymous derived-table, which is whatORDER BY
sees, and this derived-table is not the same object asOplata
.- That's why it complains about the missing column: the column simply doesn't exist anymore.
Anyway, you can order rows by a column that isn't in the
SELECT
clause, but it's a bit gnarly....- Also, note that (in ISO SQL, I don't know about MySQL), the
ORDER BY
clause can only be used in the outermost (non-CTE)SELECT
query step of a nontrivial query (because relations are sets, which are unordered).
- Also, note that (in ISO SQL, I don't know about MySQL), the
The trick is to take the existing ( IDKartoch, Total )
query-result (actually "derived table") from your current query, and wrap it in an outer-query which aliases the derived-table (allowing ORDER BY IDKartoch
while only having Total
in the outermost SELECT
clause.
Like so (tested in MySQL 5.6):
SELECT
q.Total
FROM
(
SELECT
IDKartoch
SUM(SummOpl) AS Total
FROM
Oplata
GROUP BY
IDKartoch
HAVING
SUM( Oplata.SummOpl ) >= 0
) AS q
ORDER BY
q.IDKartoch;
CodePudding user response:
You just removed the column that you wanted to ORDER BY.