SQL - GROUP BY年龄降序与出生日期

时间:2016-06-13 21:11:42

标签: sql ms-access

我试图从我的数据库中的某个表中打印选定的数据。我可以成功地做到这一点,但我必须打印按年龄和降序分组。但我不知道如何只用出生日期这样做。感谢任何帮助,我的SQL显示在下面。

SELECT pet_id, Name, Type, Breed, Born
FROM pet
WHERE Born
BETWEEN '1999' AND '2001'
GROUP BY 

请随时提问。我没有尝试任何事情,因为我不知道从哪里开始。

3 个答案:

答案 0 :(得分:3)

我认为你想 ORDER BY 年龄而不是 GROUP BY 。您没有建议分组的聚合函数。

所以:

SELECT pet_id, Name, Type, Breed, Born
FROM pet
WHERE Born BETWEEN '1999' AND '2001'
ORDER BY Born ASC;

答案 1 :(得分:0)

如果实际年龄是查询中的重要输出,则此问题和答案可能有助于使用出生日期和当前日期计算年龄: How to calculate age (in years) based on Date of Birth and getDate()

根据您的初始查询以及您要求提供数据的内容,我认为仅按订单

不需要群组
SELECT pet_id, Name, [Type], Breed, Born, 
DATEDIFF(hour, Born, GETDATE())/8766 as 'Age'
FROM pet
WHERE Born
BETWEEN '1999' AND '2001'
ORDER BY DATEDIFF(hour, Born, GETDATE())/8766 DESC

答案 2 :(得分:0)

如果您尝试在MS Access中运行此SQL脚本,请尝试以下操作:

SELECT pet_id, Name, Type, Breed, Born
FROM pet
WHERE Born BETWEEN '1999' AND '2001'
ORDER BY DateDiff("yyyy",DateSerial([Born],1,1),DateSerial(Year(Date()),1,1)) DESC;

我假设'Born'字段实际上不是日期字段类型,而是数字类型或文本类型。