如何获得三个字段(一个记录),每个字段在同一个字段上计算不同的条件?

时间:2014-04-17 08:58:15

标签: sql

我有:

CREATE TABLE Vote
    (`pid` int, `choice` varchar(10))
;

INSERT INTO Vote
    (`pid`, `choice`)
VALUES
    (1, 'a'),
    (2, 'b'),
    (3, 'ana'),
    (4, 'aya'),
    (5, 'ayna'),
    (6, 'anya'),
    (7, 'x'),
    (8, 'y'),
    (9, 'z')

我试图找出包含多少选择' n'但不是' y,包括多少' y'但不是' n'有多少包括两者或包括没有。 这就是我所拥有的:

SELECT COUNT(v1.choice) AS n_not_y,COUNT(v2.choice) AS y_not_n,COUNT(v3.choice) AS rest
FROM Vote v1,Vote v2,Vote v3
WHERE v1.choice LIKE '%n%' AND v1.choice NOT LIKE '%y%' AND
      v2.choice LIKE '%y%' AND v2.choice NOT LIKE '%n%' AND
     ( (v3.choice NOT LIKE '%y%' AND v3.choice NOT LIKE '%n%') OR
     (v3.choice LIKE '%y%n%' OR v3.choice LIKE '%n%y%') )

但是你可以看到here它给出一行显示12,12,12。

4 个答案:

答案 0 :(得分:1)

您的结果显示12,12,12的原因是count获取返回的行数,无论其值如何。

您可以使用CASE,如下所示

SELECT 
SUM(CASE WHEN v1.choice LIKE '%n%' AND v1.choice NOT LIKE '%y%' THEN 1 ELSE O) AS n_not_y
SUM(CASE WHEN v2.choice LIKE '%y%' AND v2.choice NOT LIKE '%n%' THEN 1 ELSE O) AS y_not_n

等等

答案 1 :(得分:0)

由于这些是(逻辑上)三个单独的查询,因此基本上最有意义的是,单独运行它们并组合结果:

SELECT 
  (select count(*) from Vote 
   where choice LIKE '%n%' AND choice NOT LIKE '%y%') as n_not_y,
  (select count(*) from Vote 
   where choice NOT LIKE '%n%' AND choice LIKE '%y%') as y_not_n,
  (select count(*) from Vote 
   where (choice NOT LIKE '%y%' AND choice NOT LIKE '%n%') 
      OR (choice LIKE '%y%n%' or choice LIKE '%n%y%')) as rest

工作示例here

答案 2 :(得分:0)

这就是你要找的东西

SQlFiddle

答案 3 :(得分:0)

SELECT  SUM(CASE WHEN (V.choice LIKE '%n%'
AND V.choice NOT LIKE '%y%') THEN 1 ELSE 0 END)  AS n_not_y,
SUM(CASE WHEN (V.choice LIKE '%y%'
AND V.choice NOT LIKE '%n%') THEN 1 ELSE 0 END)  AS y_not_n
,SUM(CASE WHEN ((V.choice NOT LIKE '%y%' AND V.choice NOT LIKE '%n%') OR
     (V.choice LIKE '%y%n%' OR V.choice LIKE '%n%y%')) THEN 1 ELSE 0 END)
AS rest

FROM Vote V