I receive the syntax error message when I try to execute the code shown below
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'join'.
Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'order'.
But when I execute the 2nd query without the brackets () the results are ok. So when I execute the query in a new query window with the brackets in place, I receive this message. A query must be able to run within brackets ?!? Thanks for reading (and hopefully answering XD) my question.
I tried to add spaces for readability, I hope it works.
SELECT
faknr, tot_bdr as verkooporderbedrag
FROM
[001].[dbo].[frhkrg] faktuur
WHERE
dagbknr = 70
JOIN
(SELECT
SUM(amutas.bedrag) AS totaalbedrag_regels,
amutak.bkstnr, amutas.reknr, amutas.faktuurnr AS faknr
FROM
[001].[dbo].[amutak]
INNER JOIN
[amutas] ON amutak.bkstnr = amutas.bkstnr
WHERE
amutak.dagbknr = 90
AND status NOT IN ('V', 'O')
AND amutas.reknr = 1160
GROUP BY
amutak.bkstnr, amutak.bkstnr, amutas.reknr, amutas.faktuurnr
ORDER BY
amutak.bkstnr DESC) memoriaal ON faktuur.faknr = memoriaal.faknr
I've changed the query to the following:
SELECT
faktuur.faknr, tot_bdr AS verkooporderbedrag, SUM(totaalbedrag_regels) AS Totaalbedrag_verdeling
FROM [001].[dbo].[frhkrg] faktuur
JOIN
(SELECT
SUM(amutas.bedrag) AS totaalbedrag_regels,amutak.bkstnr,amutas.reknr,amutas.faktuurnr AS faknr
FROM
[001].[dbo].[amutak] INNER JOIN [amutas] ON amutak.bkstnr = amutas.bkstnr
WHERE
amutak.dagbknr = 90 AND status NOT IN ('V', 'O') AND amutas.reknr = 1161
GROUP BY
amutak.bkstnr,amutak.bkstnr,amutas.reknr,amutas.faktuurnr) memoriaal
ON faktuur.faknr = memoriaal.faknr
GROUP BY
faktuur.faknr,tot_bdr,totaalbedrag_regels
ORDER BY
faknr
Although my last GROUP BY statement, he still doesn't SUM (and GROUP) the results correctly. Several records are still separate:
faknr verkooporderbedrag Totaalbedrag_verdeling
14700218 5115 4880,05
14700218 5115 234,95
The data type of "Totaalbedrag_verdeling" is a number (I can do mathematical actions with it) and the other two values are the same... Someone has an update?
/ME STUPID: A column that must be SUM (or MAX etc) may not be included in the GROUP BY statement ....