我要做的是从数据库中查询所有唯一的地区名称,并在每个地区名称上获取相应的MIN
和MAX
ID
。
这就是我现在所拥有的:
SELECT DISTINCT DISTRICTNAME,
(SELECT MIN(`ID`)
FROM [DATABASE_NAME]
WHERE DISTRICTNAME = DISTRICTNAME) AS 'MIN',
(SELECT MAX(`ID`)
FROM [DATABASE_NAME]
WHERE DISTRICTNAME = DISTRICTNAME) AS 'MAX'
FROM [DATABASE_NAME]
WHERE [CONDITION]
ORDER BY DISTRICTNAME;
问题:MIN
和MAX
列显示相同的值。我不太确定我的内部查询的WHERE
子句。我认为这就是问题所在。
帮助?
答案 0 :(得分:3)
使用GROUP BY
子句
SELECT DISTRICTNAME, MIN(`ID`) AS 'MIN', MAX(`ID`) AS 'MAX'
FROM [DATABASE_NAME]
WHERE [CONDITION]
GROUP BY DISTRICTNAME
ORDER BY DISTRICTNAME;;