mysql查询选择不同的记录条件?

0wi1tuuw  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(449)

我有这样的table结构。。 ext_no , value .. 我想在条件下选择不同的记录..比如 ext_no 不止两个,如果且仅当所有这些
ext_no value 是零。。我想要下面给出的预期结果…比如。。如何写mysql查询这个。。?任何帮助都将不胜感激。。提前谢谢。。
表结构:

CREATE TABLE `test` (
  `ext_no` int(5) default NULL,
  `value` int(3) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `test`
--

INSERT INTO `test` (`ext_no`, `value`) VALUES
(12133, 0),
(12133, 0),
(12133, 0),
(22222, 0),
(44226, 0),
(44226, 0),
(44226, 1),
(44226, 2),
(99902, 1),
(99902, 2),
(99902, 3),
(11505, 0),
(11505, 0),
(11505, 0),
(11505, 0);

预期结果:

ext_no  value
12133     0
11505     0

编辑:我试过了-

select distinct ext_no, value from test where value ='0' order by ext_no DESC;
pgvzfuti

pgvzfuti1#

试试这个

SELECT t.ext_no, COUNT(*)
FROM test t
WHERE NOT EXISTS (
    SELECT 1
    FROM test
    WHERE ext_no = t.ext_no AND ext_no > 0
)
GROUP BY t.ext_no
HAVING COUNT(*) > 2
u7up0aaq

u7up0aaq2#

count 跳过 null 价值观。所以你可以 countcase 值所在的表达式 0 ,然后使用 having 检查此计数是否等于总计数的条件:

SELECT   ext_no, MAX(value)
FROM     test
GROUP BY ext_no
HAVING   COUNT(*) > 2 AND 
         COUNT(*) = COUNT(CASE value WHEN 0 THEN 1 END)
68de4m5k

68de4m5k3#

您可以使用group by和having子句来尝试此操作:

SELECT
    ext_no,
    SUM(value) as value
FROM
    test
GROUP BY
    ext_no
HAVING
    count(*) > 2 AND SUM(value) = 0

相关问题