我在Access 2013中构建了一个SQL查询。这是我的查询:
SELECT
COUNT(Age) FROM Members AS [Under 12] WHERE Age <= 12,
COUNT(Age) FROM Members AS [13-18] WHERE Age BETWEEN 13 AND 18
但我一直收到这个错误:
查询表达式中的语法错误(逗号)&#39;年龄&lt; = 12, COUNT(年龄)来自SukkotMembers AS [13-18]年龄在13和18之间`
问题在于第二行末尾的逗号,但我不明白为什么。当我只运行一行时它工作正常。我是SQL新手,所以你知道。
此外,我刚刚意识到AS [Under 12]
和AS [13-18]
无效,我也不知道为什么
答案 0 :(得分:4)
首先:您使用的语法不是有效的SQL,因为您有多个FROM
子句是不允许的;这同样适用于where
子句,顺便说一下,它对整个集合起作用。
你不能只是将SQL和补丁一起取出来获得一个有效的查询 - 你必须坚持一个相当严格和明确定义的语法。
您想要的是使用返回标量值的子查询或使用条件计数:
SELECT
COUNT(IIF(Age<=12,age,null)) AS [Under 12]
,COUNT(IIF(Age BETWEEN 13 AND 18,age,null)) AS [13-18]
FROM Members
此外,FROM Members AS [13-18]
为表分配别名,而不是列。
使用子查询(我猜可能是你的意图):
SELECT DISTINCT
(SELECT COUNT(*) FROM MEMBERS WHERE AGE<=12) AS [UNDER 12] ,
(SELECT COUNT(*) FROM MEMBERS WHERE AGE BETWEEN 13 AND 18) AS [13-18]
FROM MEMBERS
答案 1 :(得分:3)
你也可以求和:
SELECT
Sum(Abs(Age <= 12)) AS [Under 12],
Sum(Abs(Age BETWEEN 13 AND 18)) AS [13-18]
FROM
Members