如何计算复杂查询的列中相同值的数量?

时间:2019-02-18 11:08:52

标签: mysql

如何计算复杂查询中一列中相同值的数量?

我使用以下命令:

SELECT 
Table,id,first,second,third,code
FROM (
SELECT 't1' AS 'Table',id, first, second, third, code FROM x_table1
UNION ALL
SELECT 't2' AS 'Table',id,first,second,third,code FROM x_table2
) tbl
GROUP BY id, first, second, third, code 
HAVING count(*) = 1
ORDER BY id

查询结果:

     id
t1 | 10 | something1 | something | something1 | something 
t2 | 10 | something1 | something | something2 | something
t1 | 33 | something3 | something | something  | something

结果,我得到了该列中的记录数。现在,我需要在其中添加具有相同ID的列。

示例,我想要第一列:

count   id
2     | t1 | 10 | something1 | something | something1 | something 
2     | t2 | 10 | something1 | something | something2 | something
1     | t1 | 33 | something3 | something | something  | something

能给我个建议吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

正确的解决方案:

SELECT 
(
SELECT COUNT(id_zaznam) FROM 
(
    SELECT * FROM x_table1
    UNION ALL
    SELECT * FROM x_table2
) temp WHERE temp.id_zaznam = tbl.id_zaznam
) AS 'pocet',
Tabulka,id_zaznam,prvni,druhy,treti,kod
FROM (
SELECT 't1' AS 'Tabulka',id_zaznam, prvni, druhy, treti, kod FROM x_table1
UNION ALL
SELECT 't2' AS 'Tabulka',id_zaznam,prvni,druhy,treti,kod FROM x_table2
) tbl
GROUP BY id_zaznam, prvni, druhy, treti, kod
HAVING count(*) = 1
ORDER BY id_zaznam