Python,将case语句插入到sql查询中

时间:2013-05-17 13:28:56

标签: python sql case

我在PYTHON的SQL查询中多次使用CASE语句时遇到问题。 我想知道我是否可以删除CASE语句并创建模板,然后我可以将模板参数放回原始查询中。像这样:

case_stm_template = 
    crs.execute("""
         CASE
            WHEN level_1 = 'Corporate'
            THEN 
                CASE
                    WHEN ssr.rating = 'A' OR ssr.rating LIKE 'A[+-]'
                    THEN 'Corp A'

                    WHEN ssr.rating = 'AA' OR ssr.rating LIKE 'AA[+-]'
                    THEN 'Corp AA'

                    WHEN ssr.rating = 'BBB' OR ssr.rating LIKE 'BBB[+-]'
                    THEN 'Corp BBB'

                    ELSE NULL
                END

            WHEN level_1 = 'Government' AND level_2 = 'Provincial'
            THEN 'Prov'

            WHEN level_1 = 'Government' AND level_2 = 'Federal'
            THEN 'Canada'

            ELSE NULL
        END

        """)

把它放进

crs.execute("""
    SELECT
        ...
        case_stm_template,
        SUM(...)
    FROM ....
    WHERE ....
    GROUP BY
        case_stm_template
""".format(...))

这不起作用。谁能帮我? THX !!!

1 个答案:

答案 0 :(得分:0)

怎么样:

case_stm_template="""
     CASE
        WHEN level_1 = 'Corporate'
        THEN 
            CASE
                WHEN ssr.rating = 'A' OR ssr.rating LIKE 'A[+-]'
                THEN 'Corp A'

                WHEN ssr.rating = 'AA' OR ssr.rating LIKE 'AA[+-]'
                THEN 'Corp AA'

                WHEN ssr.rating = 'BBB' OR ssr.rating LIKE 'BBB[+-]'
                THEN 'Corp BBB'

                ELSE NULL
            END

        WHEN level_1 = 'Government' AND level_2 = 'Provincial'
        THEN 'Prov'

        WHEN level_1 = 'Government' AND level_2 = 'Federal'
        THEN 'Canada'

        ELSE NULL
    END

    """

然后

crs.execute("""
SELECT
    ...
    %s,
    SUM(...)
FROM ....
WHERE ....
GROUP BY
    %s
""" % (case_stm_template, case_stm_template))

或类似的东西。