这是我的代码
select c.number as num,
convert(varchar,c.datestart,101) as date_start,
convert(varchar,max(c.datestop),101) as date_stop,
c.name as name_ua,
cEng.name as name_eng,
cRus.name as name_rus,
citytype as city_type
from cd_city c
left join dbo.cd_cityforeign cEng on cEng.city = c.number and cEng.language =1
left join dbo.cd_cityforeign cRus on cRus.city = c.number and cRus.language =2
order by c.number;
我已经阅读了一些解决我的问题的方法,但是对我没有帮助,例如带有group by的变量对我不起作用,我不知道为什么... 我试图通过子查询来做到这一点,但我是初学者,所以我犯了一些错误... 帮帮我,伙计们! 也许我可以使用HAVING,但我仍然需要您的帮助来向我展示如何写...谢谢! 让我们为您提供更多信息,当我尝试仅查找stopdates的最大值时出现此错误。
答案 0 :(得分:4)
您正在使用不带GROUP BY的Aggregator MAX函数。但是您可以使用以下内联子查询来获得所需的结果。
SELECT c.number AS num,
CONVERT(VARCHAR, c.datestart, 101) AS date_start,
CONVERT(VARCHAR, (SELECT MAX(c2.datestop) FROM cd_city c2 WHERE c2.number = c.number), 101) AS date_stop,
c.name AS name_ua,
cEng.name AS name_eng,
cRus.name AS name_rus,
citytype AS city_type
FROM cd_city c
LEFT JOIN dbo.cd_cityforeign cEng ON cEng.city = c.number
AND cEng.language = 1
LEFT JOIN dbo.cd_cityforeign cRus ON cRus.city = c.number
AND cRus.language = 2
ORDER BY c.number;
另一个选择。你能检查这个对你有用吗?
SELECT c.number AS num,
convert(varchar,MIN(c.datestart),101) as date_start,
convert(varchar,max(c.datestop),101) as date_stop,
c.name AS name_ua,
cEng.name AS name_eng,
cRus.name AS name_rus,
citytype AS city_type
FROM cd_city c
LEFT JOIN dbo.cd_cityforeign cEng ON cEng.city = c.number
AND cEng.language = 1
LEFT JOIN dbo.cd_cityforeign cRus ON cRus.city = c.number
AND cRus.language = 2
GROUP BY c.number,
c.[name],
cEng.[name],
cRus.[name],
citytype
ORDER BY c.number;
答案 1 :(得分:0)
您应该写MAX(c.datestop)
而不是MAX(c.datestop) OVER ()
作为整体最大值。
如果您需要每个c.number的最大值,请写MAX(c.datestop) OVER (PARTITION BY c.number)
因此,您的查询将如下所示:
SELECT c.number AS num,
CONVERT(VARCHAR, c.datestart, 101) AS date_start,
CONVERT(VARCHAR, MAX(c.datestop) OVER (PARTITION BY c.number), 101) AS date_stop,
c.name AS name_ua,
cEng.name AS name_eng,
cRus.name AS name_rus,
citytype AS city_type
FROM cd_city c
LEFT JOIN dbo.cd_cityforeign cEng
ON cEng.city = c.number
AND cEng.language = 1
LEFT JOIN dbo.cd_cityforeign cRus
ON cRus.city = c.number
AND cRus.language = 2
ORDER BY
c.number
这称为窗口函数,该函数可帮助您聚合数据而无需使用group by子句的子查询。 有关更多信息,请访问https://docs.microsoft.com/ru-ru/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-2017