此处的mySQL语句尝试按年打印总发票金额。
> select YEAR(I.INV_DATE), SUM(LINE_UNITS * LINE_PRICE) as total from
> INVOICE I, LINE L where I.INV_NUMBER = L.INV_NUMBER group by 1
但如果我添加喜欢(仅打印年份大于500的那些)
> select YEAR(I.INV_DATE), SUM(LINE_UNITS * LINE_PRICE) as total from
> INVOICE I, LINE L where I.INV_NUMBER = L.INV_NUMBER group by 1
> where total > 500
给我错误消息:语法错误
我做错了什么?谢谢!
答案 0 :(得分:1)
使用HAVING
代替WHERE
SELECT....
FROM ...
GROUP BY ...
HAVING SUM(LINE_UNITS * LINE_PRICE) > 500
或者你可以将它包装在像这样的子查询中,
SELECT *
FROM
(
SELECT YEAR(I.INV_DATE), SUM(LINE_UNITS * LINE_PRICE) as total
FROM INVOICE I, LINE L
WHERE I.INV_NUMBER = L.INV_NUMBER
GROUP BY 1
) a
WHERE total > 500
答案 1 :(得分:1)
SELECT YEAR(I.INV_DATE), SUM(LINE_UNITS * LINE_PRICE) as total
FROM INVOICE I, LINE L
WHERE I.INV_NUMBER = L.INV_NUMBER
GROUP BY 1
HAVING total > 500
参见http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html
您需要将HAVING
与GROUP BY