我正在尝试实现一个SQL查询,它连接多行并返回相等值的出现次数。
ID Row_1 Row_2 Row_3
1 Value NULL NULL
2 NULL Value Value
3 NULL Value NULL
4 NULL Value2 NULL
查询应返回两行
ID Row Count
1* Value 3
4 Value2 1
第一个返回行的ID无关紧要。如果value在所有三个原始行上都是唯一的,则应返回原始ID(如结果集的第2行所示)。我必须提一下,表中有超过50,000行。它不应该花太多时间。
我尝试了几种方法,比如加入桌子。什么都没有真正解决问题。
提前致谢。
马
答案 0 :(得分:2)
首先,您可以创建一个子查询,该子查询汇编所有非空值的列表,然后加入到该值。
值列表的子查询:
SELECT row_1 AS val FROM mytable WHERE row_1 IS NOT NULL
UNION
SELECT row_2 AS val FROM mytable WHERE row_2 IS NOT NULL
UNION
SELECT row_3 AS val FROM mytable WHERE row_3 IS NOT NULL
(UNION
隐式执行DISTINCT
,因此结果列表不会有重复值。)
然后我们可以加入我们的计数:
SELECT m.id, v.val AS `row`, COUNT(*) AS `count`
FROM mytable m
INNER JOIN (
SELECT row_1 AS val FROM mytable WHERE row_1 IS NOT NULL
UNION
SELECT row_2 AS val FROM mytable WHERE row_2 IS NOT NULL
UNION
SELECT row_3 AS val FROM mytable WHERE row_3 IS NOT NULL
) v
ON v.val = m.row_1
OR v.val = m.row_2
OR v.val = m.row_3
GROUP BY v.val
答案 1 :(得分:0)
我们可以做::
Select
ID,
CONCAT(ifnull(ROW_1,''), ifnull(ROW_2,''), ifnull(ROW_3,'')) as `temp_ROW`,
count(1) as count
from table group by temp_ROW;