SQL 学习2

作者: 奔跑的笨鸟 | 来源:发表于2017-07-05 16:53 被阅读5次

    把一个按月统计表,变成按年统计

    year month amount
    1991 1 1.1
    1991 2 1.2
    1991 3 1.3
    1991 4 1.4
    1992 1 1.1
    1992 2 1.2
    1992 3 1.3
    1992 4 1.4

    用sql生成下面的表:

    year m1 m2 m3 m4
    1991 1.1 1.2 1.3 1.4
    1992 1.1 1.2 1.3 1.4
    SELECT 
        year,
        SUM(CASE
            WHEN month = 1 THEN amount
            ELSE 0
        END) AS m1,
        SUM(CASE
            WHEN month = 2 THEN amount
            ELSE 0
        END) AS m2,
        SUM(CASE
            WHEN month = 3 THEN amount
            ELSE 0
        END) AS m3,
        SUM(CASE
            WHEN month = 4 THEN amount
            ELSE 0
        END) AS m4
    FROM
        t1
    GROUP BY year;
    
    
    

    有两个表A 和B ,均有key 和value 两个字段,如果B 的key 在A 中也有,就把B 的value 换为A 中对应的value

    这道题的SQL 语句怎么写?

    UPDATE b 
    SET 
        b.value = (SELECT 
                a.value
            FROM
                a
            WHERE
                a.key = b.key)
    WHERE
        b.key IN (SELECT 
                a.key
            FROM
                a);
    
    

    相关文章

      网友评论

        本文标题:SQL 学习2

        本文链接:https://www.haomeiwen.com/subject/izoxhxtx.html