嗨,我试图计算相同值的行数,
id,value
1 | a
2 | b
3 | c
4 | d
5 | e
我的查询是
select value, count(*) as Count from mytable where id in('4','2','4','1','4') group by value having count(*) > 1
我的预期输出,
value,Count
d | 3
b | 1
a | 1
谢谢,任何帮助将不胜感激
答案 0 :(得分:0)
试试:
SELECT value, count(value) AS Count
FROM mytable m
WHERE value = m.value
GROUP BY value
答案 1 :(得分:0)
SELECT t.id, t.value, COUNT(t.id)
FROM
test t
JOIN
( SELECT 1 AS id
UNION ALL SELECT 3
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 1
UNION ALL SELECT 1 ) AS tmp
ON t.id = tmp.id
GROUP BY t.id
上的示例
另请参阅:Force MySQL to return duplicates from WHERE IN clause without using JOIN/UNION?
当然,您的IN参数将是动态的,因此您必须为tmp表生成相应的SQL语句。
这是SQL的唯一方法。另一种可能性就是让您的查询与您的问题一样,然后以编程方式将行与传递给IN参数的计数相关联。