我有一个包含这些列的表(MS SQL-Server 2008);
city cityDate
和这样的行;
我想要的是订购日期栏(desc)并获取城市的不同价值。因此,应该是;
我试过了;
select distinct(city) from TableCity order by cityDate desc
但输出是;
消息145,级别15,状态1,行1 ORDER BY项目必须出现在 如果指定了SELECT DISTINCT,则选择列表。
答案 0 :(得分:4)
您只需要使用group by而不是distinct:
假设T是你的表:
WITH T as
(
SELECT 'Porto' City,'20.11.1988' CityDate UNION ALL
SELECT 'Porto' City,'19.11.1988' CityDate UNION ALL
SELECT 'Lisbon' City,'21.11.1988' CityDate
)
- 测试1:
select City,CityDate from T GROUP BY City,CityDate Order by CityDate DESC
- 结果:这仍然显示三行,因为波尔图的城市日期不一样,但如果波尔图城市日期相同,它将只显示两行。
City CityDate
Lisbon 21.11.1988
Porto 20.11.1988
Porto 19.11.1988
- 测试2:
select T2.City
FROM
(select City from T GROUP BY City,CityDate) as T2
GROUP BY T2.City
OR
你可以使用CTE:
With T as
(
select City from YourTable GROUP BY City,CityDate
)
select City FROM T group by City
- 结果:
City
Lisbon
Porto
此致
答案 1 :(得分:0)
我在手机上这样做,所以以下是未经测试的,但它应该可以正常工作
SELECT T2.city
FROM ( SELECT city, MAX(cityDate) AS maxDate
FROM T
GROUP BY city
ORDER BY maxDate desc ) AS T2