0

如果我们有两个这样的表

CREATE TABLE ta(`ID` int, `name` char(10));
INSERT INTO ta (`ID`, `name`)
VALUES
    (1, 'A'),
    (2, 'A'),
    (3, 'B'),
    (4, 'C'),
    (5, 'B');

CREATE TABLE yourtable(`ID` int, `Val` int);
INSERT INTO yourtable (`ID`, `Val`)
VALUES
    (1, 10),
    (1, 20),
    (1, 30),
    (1, 30),
    (2, 10),
    (2, 20),
    (3, 20),
    (3, 20),
    (4, 10),
    (4, 20),    
    (5, 10),
    (5, 20),
    (5, 30);

而且,我需要name使用两个表对值进行分组。而且,对于条件 val=10 或 val=30 它工作正常。http://sqlfiddle.com/#!2/9c099/1

select name, count(distinct t1.id)
from yourtable as t1, ta
where t1.id=ta.id
AND (val=10 OR val=30)
group by name

但是,对于条件(val=10 AND val!=30)我该如何查询呢?为此,输出应该是

   Count
A  1
B  0
C  1

举个例子:以name=A为例,这里我们得到ID=1,2。因此,现在在您的表中,我们有 5 行 ID=1,2。对于 ID=1,val=10,20,20。对于 ID=2,val=10,20。这里只有 ID=2 满足 (val=10 AND val!=30) 所以,对于 name=A count=1

4

3 回答 3

0

您需要一个子查询yourtable来确定 ID 是否满足条件,并将其加入ta

select name, SUM(Satisfies)
from ta, (
    SELECT distinct ID, CASE WHEN ID NOT IN (
        SELECT ID FROM yourtable
        WHERE Val = 30 )
    AND ID IN (
        SELECT ID FROM yourtable
        WHERE Val = 10 ) THEN 1 ELSE 0 END Satisfies
    FROM yourtable
) t1
WHERE t1.id=ta.id
group by name

SQL小提琴

于 2013-08-08T13:46:35.600 回答
0

不是很好但工作:

SELECT name, max(occ) occurencies
  FROM (SELECT name, count(distinct t1.id) as occ
          FROM yourtable as t1, ta
         WHERE t1.id=ta.id
           AND val=10 
           AND NOT EXISTS (SELECT name 
                             FROM yourtable as t2 
                            WHERE t2.id=ta.id AND t2.val=30)
        GROUP BY name
        UNION
        SELECT name, 0 as occ
          FROM yourtable as t1, ta
         WHERE t1.id=ta.id
           AND val=10 
           AND EXISTS (SELECT name 
                         FROM yourtable as t2 
                        WHERE t2.id=ta.id AND t2.val=30)) as base
 GROUP BY name;

查看:http ://sqlfiddle.com/#!2/9c099/192

ps:稍微好一点:

 SELECT ta.name, COALESCE (occ, 0)
   FROM ta
   LEFT JOIN (SELECT name, count(distinct t1.id) as occ
                FROM yourtable as t1, ta
               WHERE t1.id=ta.id
                 AND val=10 
                 AND NOT EXISTS (SELECT name 
                                   FROM yourtable as t2 
                                  WHERE t2.id=ta.id 
                                    AND t2.val=30)
               GROUP BY name) AS base ON (base.name = ta.name)
  GROUP BY name;    

http://sqlfiddle.com/#!2/9c099/212

:)

于 2013-08-08T13:53:20.580 回答
0
SELECT ta.name
     , COUNT(DISTINCT t2.val)
  FROM yourtable t1 
  LEFT
  JOIN yourtable t2
    ON t2.id = t1.id 
   AND t2.val IN (30) -- <-- things to exclude
  LEFT
  JOIN ta 
    ON ta.id = t1.id 
 WHERE t1.val IN (10) -- <-- things to include
 GROUP
    BY name;

NAME COUNT(T2.VAL)
A    1
B    1
C    0

http://sqlfiddle.com/#!2/9c099/169

于 2013-08-08T13:20:09.703 回答