SQL查询过滤器,如果计数

时间:2015-08-19 12:43:49

标签: mysql sql

我有一张这样的表

user  |  app
name1   app1
name1   not an app
name1   app1
name1   app2
name2   not an app
name3   app1
name3   app3
name4   app1
name4   not an app2
name5   app1
name5   not an app
name5   not an app2

我需要获得用户拥有app1和至少一种类型的应用程序“非应用程序”的情况,我将在此示例中调用的不是应用程序而不是app2。

我需要得到这样的东西:

user
name1
name4 
name5 

我试图过滤WHERE而不是LIKE(s)然后ORDER BY我认为下一步就像HAVING COUNT DISTINCT app = app1> 2但是我迷失在这里,只有在有app1时才开始计算......

理想情况下,id也想知道

user name: list of apps
user name1:  not an app, ...
user name4:  not an app2, ...
user name5:  not an app1, not an app2, ...

4 个答案:

答案 0 :(得分:3)

试试这个

select user  from table
where app = 'app1' or app like 'not an app%'
group by user
having count(distinct app)>=2

答案 1 :(得分:1)

我不确定你的真正目标是什么,因为如果你需要来获取用户拥有app1并且至少有一个"而不是应用程序"

您的预期结果

user
name1
name4 
name5 

错了。

检查我的小提琴:http://sqlfiddle.com/#!9/cbb566/7

SELECT `user`
FROM table1 t1
GROUP BY `user`
HAVING SUM(IF(`app`='app1',1,0))>0
 AND SUM(IF(`app`='not an app',1,0))>0

更新如果您需要以'不是应用

开头的任何内容

你可以http://sqlfiddle.com/#!9/cbb566/11

SELECT `user`
FROM table1 t1
GROUP BY `user`
HAVING SUM(IF(`app`='app1',1,0))>0
 AND SUM(IF(`app` LIKE 'not an app%',1,0))>0

答案 2 :(得分:0)

这应该有用;了解"喜欢"运算符和子查询

select user, app
from tablename
where user in 
(select user
from tablename
where app = 'app1')
and app like '%not an app%'
order by user

答案 3 :(得分:0)

尝试下面:我希望它也可以在大数据上产生预期效果

SELECT DISTINCT( T1.[User] )
FROM dbo.Temp T1
WHERE App = 'app1'
AND EXISTS ( SELECT [User] FROM dbo.Temp WHERE [User] = T1.[User] AND [App] LIKE '%not an app%' )