I need to count Companies that have Field_ID "134" but don't have other Field_IDs; in my example Company with ID 2 has only 1 field "134" so I need this to be counted, but company with ID 3 has field "134" but other fields as well, so I want to exclude this one from counting.
Table ID Company_ID Field_ID
1 1 130
2 1 131
3 2 134
4 3 134
5 3 137
6 3 140
MySQL Workbench
SELECT count(distinct id) FROM company
where field_id = 1
I need to count Companies that have Field_ID "134" but don't have other Field_IDs; in my example Company with ID 2 has only 1 field "134" so I need this to be counted, but company with ID 3 has field "134" but other fields as well, so I want to exclude this one from counting.
Expected result should be count of "1"
Table ID Company_ID Field_ID
1 1 130
2 1 131
3 2 134
4 3 134
5 3 137
6 3 140
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(Company_ID INT NOT NULL,Field_ID INT NOT NULL,PRIMARY KEY(company_id,field_id));
INSERT INTO my_table VALUES
(1,130),
(1,131),
(2,134),
(3,134),
(3,137),
(3,140);
SELECT DISTINCT x.*
FROM my_table x
LEFT
JOIN my_table y
ON y.company_id = x.company_id
AND y.field_id <> x.field_id
WHERE x.field_id = 134
AND y.company_id IS NULL;
+------------+----------+
| Company_ID | Field_ID |
+------------+----------+
| 2 | 134 |
+------------+----------+
You can also use HAVING MAX(field_id) = 134 AND MIN(field_id) = 134, or variations on that theme
You can group by Company_ID
and count the number of Field_ID
, then select only the ones that have that count = 1 :
Schema (MySQL v5.7)
CREATE TABLE test (
`Table ID` INTEGER,
`Company_ID` INTEGER,
`Field_ID` INTEGER
);
INSERT INTO test
(`Table ID`, `Company_ID`, `Field_ID`)
VALUES
(1, 1, 130),
(2, 1, 131),
(3, 2, 134),
(4, 3, 134),
(5, 3, 137),
(6, 3, 140);
Query #1
SELECT t.Company_ID
FROM test t
GROUP BY t.Company_ID
HAVING COUNT(t.Field_ID) = 1
AND MAX(t.Field_ID) = 134;
Output
| Company_ID |
| ---------- |
| 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.