获取平均每年的单位并过滤查询

时间:2019-10-23 10:28:15

标签: sql-server filter average

我需要代码方面的帮助,我希望从下表中获得每个城市和每年的平均价格。

    Date    City    Price
 10/23/2018 Leon    1088
 2/27/2018  NewYork 1312
 4/19/2017  Texas   1303
 4/19/2017  London  1303
 4/19/2019  NewYork 1303
 2/12/2018  Leon    1251
 4/7/2017   Leon    1170
 3/20/2019  London  1650
 12/18/2017 Texas   1358
 2/18/2019  Leon    1088
 7/3/2017   NewYork 1391
 8/8/2019   Texas   830
 4/5/2018   London  1869.5
 1/29/2018  London  1169
 8/9/2019   Texas   1130

平均价格应按每年每个城市计算。 结果应按年份分组,并按每个城市显示,如下所示:

City       Avg2017    Avg2018    Avg2019
Leon        1170      1169.5     1088
London      1303      1519.25    1650
New York    1391      1312       1303
Texas       1330.5     0         1390

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

尝试动态查询

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(YEAR(c.[Date])) 
        FROM YourTableName c
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')



SET @query = 'SELECT City, ' + @cols + ' FROM 
(

SELECT City,YEAR([Date]) AS AvgYear,AVG(Price) AS Price
FROM YourTableName
GROUP BY City,YEAR([Date])

)AS CTEs

 PIVOT (
          MAX(Price)
          FOR AvgYear in (' + @cols + ')
       ) p
             '

EXECUTE(@query)

答案 1 :(得分:1)

尝试通过枢纽逻辑使用聚合:

SELECT
    City,
    AVG(CASE WHEN CONVERT(varchar(4), Date, 120) = '2017' THEN Price END) AS Avg2017,
    AVG(CASE WHEN CONVERT(varchar(4), Date, 120) = '2018' THEN Price END) AS Avg2018,
    AVG(CASE WHEN CONVERT(varchar(4), Date, 120) = '2019' THEN Price END) AS Avg2019
FROM yourTable
WHERE
    CONVERT(varchar(4), Date, 120) IN ('2017', '2018', '2019')
GROUP BY
    City;