[英]Count occurrences across each row in mySQL
I have been racking my brain on how to count how often a string occurs across each row, and ultimately update another column. 我一直在思考如何计算每行中出现一个字符串的频率,并最终更新另一列。
If I have the questions table that contains a sponsors answers for each question in a record: 如果我有一个问题表,其中包含发起人的记录中每个问题的答案:
+-------------+-----+-----+-----+-----+-----+ | response_id | q1 | q2 | q3 | q4 | q5 | +-------------+-----+-----+-----+-----+-----+ | 1 | Yes | N/A | Yes | No | Yes | | 2 | No | Yes | No | Yes | N/A | | 3 | Yes | No | No | N/A | Yes | +-------------+-----+-----+-----+-----+-----+
Is it possible to do this: 是否有可能做到这一点:
+-------------+-----+-----+-----+-----+-----+-----+----+-----+ | response_id | q1 | q2 | q3 | q4 | q5 | Yes | No | N/A | +-------------+-----+-----+-----+-----+-----+-----+----+-----+ | 1 | Yes | N/A | Yes | No | Yes | 2 | 1 | 1 | | 2 | No | Yes | No | Yes | N/A | 2 | 1 | 1 | | 3 | Yes | No | No | N/A | Yes | 1 | 1 | 2 | +-------------+-----+-----+-----+-----+-----+-----+----+-----+
I am importing this data from an csv to a Laravel application. 我正在将此数据从csv导入到Laravel应用程序。 It if's not possible, is there a way I can rearrange this data to get to the end result.
如果不可能的话,有没有办法我可以重新排列这些数据以获得最终结果。
Thanks! 谢谢!
You can use the update query like the one below: 您可以使用以下更新查询:
update responses set Yes = IF(q1='Yes',1,0)
+ IF(q2='Yes',1,0)
+ IF(q3='Yes',1,0)
+ IF(q4='Yes',1,0)
+ IF(q5='Yes',1,0);
This will update the existing rows (here's SQL Fiddle ). 这将更新现有的行(这里是SQL Fiddle )。 For the new rows, you can write something in the application itself, to caculate these values before a row is inserted.
对于新行,您可以在应用程序本身中编写一些内容,以在插入行之前计算这些值。
Here the hole query for you: 在此为您查询孔:
SELECT
response_id
,q1,q2,q3,q4,q5
, IF ( q1 = 'Yes', 1,0)+IF ( q2 = 'Yes', 1,0)+IF ( q3 = 'Yes', 1,0)+IF ( q4 = 'Yes', 1,0)+IF ( q5 = 'Yes', 1,0) AS `Yes`
, IF ( q1 = 'No', 1,0)+IF ( q2 = 'No', 1,0)+IF ( q3 = 'No', 1,0)+IF ( q4 = 'No', 1,0)+IF ( q5 = 'No', 1,0) AS `No`
, IF ( q1 = 'N/A', 1,0)+IF ( q2 = 'N/A', 1,0)+IF ( q3 = 'N/A', 1,0)+IF ( q4 = 'N/A', 1,0)+IF ( q5 = 'N/A', 1,0) AS `N/A`
FROM my_table;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.