简体   繁体   中英

Mysql query to select Distinct Records on conditions?

i have table structure like this.. ext_no , value .. i want to select distinct records on condition..like when count of ext_no is more than two and IF AND ONLY IF all that ext_no value is zero.. I Want Expected Result Given below...like.. how to write mysql query this this..? any help would be appreciated.. Thanks in advance..

Table Structure:

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);

Expected Result:

ext_no  value
12133     0
11505     0

Edit: i Tried-

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

count skips null values. So you can count a case expression where the value is 0 , and then use a having condition to check that this count is equal to the total count:

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

You can try this one, using group by and the having clause:

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM