像MySQL一样使用

时间:2016-07-18 13:46:18

标签: mysql

我想在group by中使用类似'like'的逻辑。

例如,数据将是:

John1 
John2 
John3
Steve1
Steve2

我希望输出如下:

John 3

我搜索了解决方案,但我得到了静态文本。我将在'having'子句中动态传递参数值。 (就像在这里,我将通过'约翰')。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

如果您想搜索LIKE John的内容,请使用

SELECT yourColumn 
FROM yourTable 
WHERE yourColumn LIKE '%John%';

这是使用sql的方法。

如果您想对数据进行分组,您仍然可以在通过WHERE过滤后对其进行分组。

SELECT yourColumn, SUM(aggregatedColumn) 
FROM yourTable 
WHERE yourColumn LIKE '%John%' 
GROUP BY yourColumn;

之后,您可以使用HAVING按照某些重复进行过滤。

SELECT yourColumn, SUM(aggregatedColumn) 
FROM yourTable 
WHERE yourColumn LIKE '%John%' 
GROUP BY yourColumn
HAVING SUM(aggregatedColumn) > 12;

(我认为)您正在寻找这样的查询:

SELECT yourColumn, MAX(occurrences)
FROM yourTable 
WHERE yourColumn LIKE '%John%' 
GROUP BY yourColumn;

答案 1 :(得分:0)

假设您的数据是这样的:

yourtable:

yourfield
John1 
John2 
John3
Steve1
Steve2

然后你可以用某种野蛮的方式使用COUNTGROUP BY

SELECT
Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','') AS NAME,
COUNT(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','')) AS NAME_COUNT
FROM yourtable
GROUP BY Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','')

输出:

NAME    NAME_COUNT
John    3
Steve   2

SQL小提琴:http://sqlfiddle.com/#!9/64506f/1/0

使用LIKE

SELECT
Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','') AS NAME,
COUNT(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','')) AS NAME_COUNT
FROM yourtable
WHERE yourfield LIKE '%john%'
GROUP BY Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(yourfield,'9',''),'8',''),'7',''),'6',''),'5',''),'4',''),'3',''),'2',''),'1',''),'0','')