我在SQL中遇到查询问题。我需要生成的查询是输出过去一个月销售的最昂贵汽车的详细信息。
到目前为止我的SQL代码如下:
SELECT CarMake, MAX(CFSSellingPrice) AS ['PriceOfCar']
FROM CarForSale
WHERE CFSSoldDate BETWEEN CVDATE('01/02/2013') AND CVDATE('01/03/2013')
GROUP BY CarMake;
我遇到的问题是输出多辆车,并且在过去一个月内也没有正确生产最贵的车。
任何帮助都会非常感激,即使有人能指出我正确的方向。
感谢您的时间,
Alyn :)
答案 0 :(得分:2)
您的查询包含cvdate()
,因此我猜您使用的是MS Access。如果是这样,您可以使用top 1
查找销售最昂贵的汽车:
SELECT top 1 CarMake
, CFSSellingPrice
FROM CarForSale
WHERE CFSSoldDate BETWEEN CVDATE('01/02/2013') AND CVDATE('01/03/2013')
order by
CFSSellingPrice desc
答案 1 :(得分:0)
使用Top
关键字
SELECT Top 1 CarMake, MAX(CFSSellingPrice) AS ['PriceOfCar']
FROM CarForSale
WHERE CFSSoldDate BETWEEN CVDATE('01/02/2013') AND CVDATE('01/03/2013')
GROUP BY CarMake;
答案 2 :(得分:0)
尝试下面的
SELECT CarMake, MAX(CFSSellingPrice) AS ['PriceOfCar']
FROM CarForSale
WHERE CFSSoldDate BETWEEN CVDATE('01/02/2013') AND CVDATE('01/03/2013');
不要使用group by
关键字...
答案 3 :(得分:0)
此查询将为您提供所有记录,例如,如果有汽车制造商转向具有相同的售价且价格范围内的最高价格。
SELECT CarMake, CFSSellingPrice
FROM CarForSale
WHERE CFSSellingPrice =
(
SELECT TOP 1 CFSSellingPrice
FROM CarForSale
WHERE CFSSoldDate BETWEEN CVDATE('01/02/2013') AND
CVDATE('01/03/2013')
ORDER BY CFSSellingPrice
)
答案 4 :(得分:0)
以下对我有用(使用format()对您的汽车和销售进行分组,并在WHERE子句中使用子查询)
能够跨越几个月的额外好处。
SELECT
format(cfs.CFSSoldDate,"yyyy mm") AS SoldMonth
, cfs.CarMake
, MAX(CFSSellingPrice) AS PriceOfCar
FROM CarsForSale AS cfs
WHERE
cfs.CFSSoldDate BETWEEN #1/1/2013# AND #3/31/2013#
AND cfs.CFSSellingPrice = (SELECT
max(c.CFSSellingPrice) FROM CarsForSale AS c
WHERE format(c.CFSSoldDate, "yyyy mm") = format(cfs.CFSSoldDate, "yyyy mm"))
GROUP BY
format(cfs.CFSSoldDate, "yyyy mm"), cfs.CarMake