问题
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;
回答1:
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)
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/52840268/mysql-query-to-select-distinct-records-on-conditions