如何使用mysql根据同一表的其他两列填充一列?

时间:2019-03-26 16:52:25

标签: mysql sql

我的数据如下(表名为botdata)

data

现在,我需要透视此数据,以使Chatsession ID作为行,而Metrics作为列。必须有一个新的列Met014,仅当Met003和Met004为1时才应显示1。以下是我正在使用的代码以及得到的结果。其他一切都很好,但是我如何正确填充Met014?

{{1}}

result

2 个答案:

答案 0 :(得分:0)

我会用SUM()来表达这句话。我认为您可以使用LEAST()做您想做的事情:

SELECT ChatSessionID, 
       SUM(Metrics = 'Met001') AS Met001,
       SUM(Metrics = 'Met002') AS Met002,
       . . . . . . . . . . . . . . . . .,
       SUM(Metrics = 'Met012') AS Met012,
       LEAST(SUM(Metrics = 'Met003'), SUM(Metrics = 'Met004')) AS Met014
FROM botdata b
GROUP BY ChatSessionID;

答案 1 :(得分:0)

如果您的列Met001至Met013只能取值为1、0或NULL,请尝试执行以下操作:

SELECT 
        T.*, (Met003 + Met004) = 2 AS Met014
    FROM
        (SELECT 
            ChatSessionID,
                Metrics = 'Met001' AS Met001,
                Metrics = 'Met002' AS Met002,
                Metrics = 'Met003' AS Met003,
                Metrics = 'Met004' AS Met004,
                Metrics = 'Met005' AS Met005,
                Metrics = 'Met006' AS Met006,
                Metrics = 'Met007' AS Met007,
                Metrics = 'Met008' AS Met008,
                Metrics = 'Met009' AS Met009,
                Metrics = 'Met010' AS Met010,
                Metrics = 'Met011' AS Met011,
                Metrics = 'Met012' AS Met012,
                Metrics = 'Met013' AS Met013
        FROM
            botdata b
        WHERE
            b.Metrics BETWEEN 'Met001' AND 'Met014'
        GROUP BY ChatSessionID) AS T;