1

我想找到最大列值,我说:

SELECT 
Segment_ID.Segment_ID,
Intensity.Date,
Intensity.NumAll,
Intensity.AverageDailyIntensCar,
MAX(Intensity.AverageDailyIntensCar) as maxvalue,
Track.the_geom
FROM Segment_ID
LEFT JOIN Track ON Segment_ID.Segment_ID=Track.Segment_ID
LEFT JOIN Intensity ON Segment_ID.Segment_ID=Intensity.Segment_ID
where (DATEPART(yy, Intensity.Date) = 2009
AND DATEPART(mm, Intensity.Date) = 08
AND DATEPART(dd, Intensity.Date) = 14)

但得到错误:

Column `Segment_ID.Segment_ID` is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 

所以我添加GROUP BY Segment_ID.Segment_ID但下一列得到相同的错误。
如何正确使用 max() 函数?

UPD

我想我问错了。Bucouse 我希望 max() 函数返回我的行并在列中设置列 MAX(Intensity.AverageDailyIntensCar) as maxvalue的最大值Intensity.AverageDailyIntensCar。这是正确的?

4

4 回答 4

2

Max是一个聚合函数,不能与列名一起使用。如果您正在使用,请Max使用 group by。

参考

于 2013-05-22T05:50:27.113 回答
2

尝试这个:

SELECT 
Segment_ID.Segment_ID,
Intensity.Date,
Intensity.NumAll,
Intensity.AverageDailyIntensCar,
MAX(Intensity.AverageDailyIntensCar)OVER() as maxvalue,
Track.the_geom
FROM Segment_ID
LEFT JOIN Track ON Segment_ID.Segment_ID=Track.Segment_ID
LEFT JOIN Intensity ON Segment_ID.Segment_ID=Intensity.Segment_ID
where (DATEPART(yy, Intensity.Date) = 2009
AND DATEPART(mm, Intensity.Date) = 08
AND DATEPART(dd, Intensity.Date) = 14)
于 2013-05-22T06:29:15.877 回答
1

试试这个——

SELECT 
    s.Segment_ID,
    i.Date,
    i.NumAll,
    MAX(i.AverageDailyIntensCar) AS maxAverageDailyIntensCar,
    t.the_geom
FROM dbo.Segment_ID s
LEFT JOIN dbo.Track t ON s.Segment_ID = t.Segment_ID
LEFT JOIN dbo.Intensity i ON s.Segment_ID = i.Segment_ID
WHERE i.Date = '20090814'
GROUP BY 
    s.Segment_ID,
    i.Date,
    i.NumAll,
    t.the_geom

更新:

SELECT 
      s.Segment_ID
    , i.[Date]
    , i.NumAll
    , mx.maxAverageDailyIntensCar
    , t.the_geom
FROM dbo.Segment_ID s
LEFT JOIN dbo.Track t ON s.Segment_ID = t.Segment_ID
LEFT JOIN dbo.Intensity i ON s.Segment_ID = i.Segment_ID
LEFT JOIN (
    SELECT 
          i.Segment_ID
        , maxAverageDailyIntensCar = MAX(i.AverageDailyIntensCar)
    FROM dbo.Intensity i
    GROUP BY i.Segment_ID
) mx ON s.Segment_ID = mx.Segment_ID
WHERE i.[Date] = '20090814'
于 2013-05-22T05:47:13.037 回答
0
;With cte AS
(
SELECT 
Segment_ID.Segment_ID,
Intensity.Date,
Intensity.NumAll,
Intensity.AverageDailyIntensCar
Track.the_geom
FROM Segment_ID
LEFT JOIN Track ON Segment_ID.Segment_ID=Track.Segment_ID
LEFT JOIN Intensity ON Segment_ID.Segment_ID=Intensity.Segment_ID
where (DATEPART(yy, Intensity.Date) = 2009
AND DATEPART(mm, Intensity.Date) = 08
AND DATEPART(dd, Intensity.Date) = 14)
)
Select *,(Select MAX(AverageDailyIntensCar) from CTE) as maxvalue
from CTE
于 2013-05-22T06:02:26.377 回答