在mysql中 - 像这样的表:
ID Name Value 1 Color Blue 1 Weight 50 1 Type Fruit 2 Color Red 2 Weight 40 3 Color Yellow
我希望获得一个具有“类型”名称/特征的不同ID的计数,以及不具有相同ID的计数。第一个(那些那个)很容易定义,但是如果我做了一个选择计数(不同的ID),其名称<> 'type' - ID 1仍将是该计数的一部分,因为它具有<>的其他行/属性'类型'。
在该示例中 - 对于distinct count ='type'的期望结果将是1(ID 1)并且对于非重复计数<> 'type'将为2(ID为2& 3)。
提前致谢。
答案 0 :(得分:0)
SELECT id FROM test GROUP BY id HAVING
CONCAT(",",CONCAT(GROUP_CONCAT(name), ","))
NOT LIKE '%,Type,%'
会在没有Type
:http://sqlfiddle.com/#!2/30837/1
(带有,
的Concat确保您不会偶然匹配XType
。)
而
SELECT COUNT(id) AS count, GROUP_CONCAT(id) AS ids
FROM(SELECT id, count(name) as count FROM test
GROUP BY id HAVING CONCAT(",",CONCAT(GROUP_CONCAT(name), ","))
NOT LIKE '%,Type,%') as temp;
会为您提供所需的点数:http://sqlfiddle.com/#!2/30837/9
答案 1 :(得分:0)
这类似于SQL Query User has one record in the table but not another one
您可以选择id不在子查询中查找类型为
的ID的位置select count(id) from table where id not in (select id from table where name = 'type')
group by id
答案 2 :(得分:0)
您可以使用以下特定任务:
select count(distinct ID) from table
where ID in (select ID from table where name='type') --- this will give you count of IDs where type exists
select count(distinct ID) from table
where ID not in (select ID from table where name='type') -- this will give you count of IDs without type
答案 3 :(得分:-1)
SELECT CASE
WHEN Name='Type' THEN 'Type'
ELSE 'Non-Type'
END Name
,ID
,COUNT(ID)
FROM Stuff
GROUP BY
CASE
WHEN Name='Type' THEN 'Type'
ELSE 'Non-Type'
END
,ID
请参阅SQLFiddle