按组合并行

时间:2016-05-05 20:54:33

标签: mysql sql merge group-by

我有来自各州气象站的天气数据。

db model

以下是我一直在运行的基本查询。

-- Weather pattern for continental US    
SELECT 
    YEAR(Date), 
    MONTH(Date),
    DataType,
    AVG(Value)
FROM 
    Station_Data 
WHERE
    Stations_ID NOT IN (
        SELECT 
            Stations.ID 
        FROM 
            Stations 
        JOIN States
            States 
        ON 
            States.ID = Stations.States_ID 
        WHERE 
            States.Name = "Alaska" OR States.Name = "Hawaii"
    ) AND
    YEAR(Date) = 2000
GROUP BY 
    YEAR(Date), 
    MONTH(Date),
    DataType;

,输出如下

Result 1

我想将输出转换为具有MMNT,MMXT,MNTM的单独列。我尝试使用Efficiently convert rows to columns in sql serverMy Sql merging rows

中提供的解决方案
-- Weather pattern for continental US    
SELECT 
    YEAR(Date), 
    MONTH(Date),
    AVG(CASE WHEN (DataType = "MMNT") THEN Value ELSE 0 END) AS MMNT,
    AVG(CASE WHEN (DataType = "MMXT") THEN Value ELSE 0 END) AS MMXT,
    AVG(CASE WHEN (DataType = "MNTM") THEN Value ELSE 0 END) AS MNTM
FROM 
    Station_Data 
WHERE
    Stations_ID NOT IN (
        SELECT 
            Stations.ID 
        FROM 
            Stations 
        JOIN States
            States 
        ON 
            States.ID = Stations.States_ID 
        WHERE 
            States.Name = "Alaska" OR States.Name = "Hawaii"
    ) AND
    YEAR(Date) = 2000
GROUP BY 
    YEAR(Date), 
    MONTH(Date),
    DataType;

但我的结果看起来像这样......

Result 2

该陈述有什么问题?

- 更新

我尝试从GROUP中删除DataType,我得到了这个结果......

Result 4

但我认为价值是错误的。

SELECT 
    AVG(Value)
FROM 
    Station_Data 
WHERE
    Stations_ID NOT IN (
        SELECT 
            Stations.ID 
        FROM 
            Stations 
        JOIN States
            States 
        ON 
            States.ID = Stations.States_ID 
        WHERE 
            States.Name = "Alaska" OR States.Name = "Hawaii"
    ) 
    AND YEAR(Date) = 2000
    AND MONTH(Date) = 1
    AND DataType = "MMNT";

Result 5

1 个答案:

答案 0 :(得分:1)

您无需按DataType分组。这就是答案。否则,您的聚合函数在该类型的单个值内工作,因此您总是将一个列设置为非零。