[英]how do I populate a column based on other two columns of the same table using mysql?
My data is as below (table name is botdata) 我的数据如下(表名是botdata)
Now i need to pivot this data to have Chatsession ID as rows and Metrics as columns. 现在我需要将此数据透视为将Chatsession ID作为行,将Metrics作为列。 There has to be a new column Met014 which should show 1 only when Met003 and Met004 is 1. Below is the code I am using and the result I am getting.
必须有一个新的列Met014,只有当Met003和Met004为1时才应显示1.下面是我正在使用的代码和我得到的结果。 Everything else is fine but how do i populate Met014 correctly?
其他一切都很好,但我如何正确填充Met014?
SELECT ChatSessionID,
COUNT(IF(Metrics = "Met001", Metrics, NULL)) AS Met001,
COUNT(IF(Metrics = "Met002", Metrics, NULL)) AS Met002,
COUNT(IF(Metrics = "Met003", Metrics, NULL)) AS Met003,
COUNT(IF(Metrics = "Met004", Metrics, NULL)) AS Met004,
COUNT(IF(Metrics = "Met005", Metrics, NULL)) AS Met005,
COUNT(IF(Metrics = "Met006", Metrics, NULL)) AS Met006,
COUNT(IF(Metrics = "Met007", Metrics, NULL)) AS Met007,
COUNT(IF(Metrics = "Met008", Metrics, NULL)) AS Met008,
COUNT(IF(Metrics = "Met009", Metrics, NULL)) AS Met009,
COUNT(IF(Metrics = "Met010", Metrics, NULL)) AS Met010,
COUNT(IF(Metrics = "Met011", Metrics, NULL)) AS Met011,
COUNT(IF(Metrics = "Met012", Metrics, NULL)) AS Met012,
COUNT(CASE WHEN Metrics="Met003" And Metrics="Met004" THEN Metrics ELSE NULL END) AS Met014
FROM
botdata b
WHERE
b.Metrics BETWEEN "Met001" AND "Met014"
GROUP BY
ChatSessionID;
I would phrase this using SUM()
. 我会用
SUM()
来表达这个。 I think you can then do what you want with LEAST()
: 我想你可以用
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;
If your columns Met001 to Met013 can only take a value of 1, 0 or NULL, try something like this: 如果您的列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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.