根据列值创建列

时间:2019-02-15 10:02:26

标签: mysql select multiple-columns

我在如何设置SELECT上有一个奇怪的问题,因此我在每个“ PRODUCT_NAME”的三个新列上收到“ DEMO”,“ PILOT”和“ LIVE”字段。 这是我现在用来获取数据的代码:

    SELECT 
    `ct`.`COUNTRY_CODE` AS `COUNTRY_CODE`,
                COUNT(CASE WHEN
            ((`lt`.`TERM_ID` = 3)
                OR (`lt`.`TERM_ID` = 5)
                OR (`lt`.`TERM_ID` = 6)
                OR (`lt`.`TERM_ID` = 10)
                OR (`lt`.`TERM_ID` = 11)
                OR (`lt`.`TERM_ID` = 15)
                OR (`lt`.`TERM_ID` = 17)
                OR (`lt`.`TERM_ID` = 20)
                OR (`lt`.`TERM_ID` = 22)
                OR (`lt`.`TERM_ID` = 19)
                OR (`lt`.`TERM_ID` = 18))
        THEN
            'DEMO' END) AS 'DEMO',
    COUNT(CASE WHEN (`lt`.`TERM_ID` = 7) THEN 'PILOT' END) AS 'PILOT',
    COUNT(CASE WHEN ((`lt`.`TERM_ID` = 1)
                OR (`lt`.`TERM_ID` = 2)
                OR (`lt`.`TERM_ID` = 4)
                OR (`lt`.`TERM_ID` = 8)
                OR (`lt`.`TERM_ID` = 9)
                OR (`lt`.`TERM_ID` = 13)
                OR (`lt`.`TERM_ID` = 14)
                OR (`lt`.`TERM_ID` = 16)
                OR (`lt`.`TERM_ID` = 23))
        THEN
            'LIVE' END) AS 'LIVE',
        COUNT(CASE WHEN (`li`.`LICENCE_START_DATE` < '2018-07-01') THEN 'OLD' END) AS 'OLD',
        `pr`.`PRODUCT_NAME` AS `PRODUCT_NAME`
FROM
    (((`country` `ct`
    JOIN `licence_term` `lt`)
    JOIN `product` `pr`)
    JOIN `licence` `li`)
WHERE
    ((`li`.`LICENCE_START_DATE` <= LAST_DAY((CURDATE() - INTERVAL 1 MONTH)))
        AND (NOT ((`li`.`LICENCE_ID` LIKE 'OCS%')))
        AND (NOT ((`pr`.`PRODUCT_NAME` like 'OCS%')))
        AND ((`li`.`LICENCE_STATUS` = 'ACTIVE') OR (`li`.`LICENCE_STATUS` = 'ISSUED'))
        AND (`ct`.`COUNTRY_ID` = `li`.`COUNTRY_ID`)
        AND (`pr`.`PRODUCT_CODE` = `li`.`PRODUCT_CODE`)
        AND (`lt`.`TERM_ID` = `li`.`LICENCE_TERM_ID`))
GROUP BY `ct`.`COUNTRY_NAME` , `pr`.`PRODUCT_NAME`

因此,我尝试针对每种情况在名称上添加一个控件,例如:

`pr`.`PRODUCT_NAME` LIKE 'whatever'

很显然,“ case when”子句的数量增加了一倍,以便一行全部接收数据。但这似乎无法正常工作,因为它为我提供的数据与其他初始数据相同。

简而言之:我需要了解每个国家的“演示”,“飞行员”和“现场”,共7列。

如果有帮助,我向您显示MySQL上的表格: Table

0 个答案:

没有答案