1.数据表有两个字段 bus_id 和 record_id ,record_id 唯一不重复,bus_id 可以对应多个 record_id 。现求 record_id 的数量,多个 bus_id 对应的 recordId 算一个数量。 2.不能直接求去重后 bus_id 的数量,其他业务可能没有 bus_id
![]() | 1 cwcc 2022-01-05 10:59:09 +08:00 1 我没太懂,record_id 都唯一不重复了,直接 count 应该就好?(或者你把唯一不重复的这个字段没设置成 primary ?那就不行) 终极解决:3NF |
![]() | 2 Xusually 2022-01-05 11:01:04 +08:00 最简单的 COUNT 满足不了么?还是我没理解需求? |
![]() | 3 sunhelter 2022-01-05 11:01:18 +08:00 不能直接去重就分别 union 咯 SQL Server 可以这么写: select SUM(ct) select COUNT(1) ct from table where ISNULL(bus_id,'')!='' group by bus_id union all select COUNT(1) from table where ISNULL(bus_id,'')='' |
![]() | 4 sunhelter 2022-01-05 11:02:11 +08:00 上面的 SQL 在 SUM(ct)后加个括号,到结尾加反括号 |
![]() | 5 fragrans23 OP @crazywhalecc 但是,如果一个 bus_id 对应多个 record_id,这种情况计数 record_id 只记一个,例如一个 bus_id 对应两个 record_id,count(record_id)时,只记一次。直接 count 会记录两次吧 |
6 zheng96 2022-01-05 12:23:57 +08:00 前提是 bus_id 和 record_id 本身不会重复,如果会重复可以在 then 后头拼接个前缀区分下 select count( distinct( case when record_id is null then null when bus_id is null then record_id else bus_id end ) ) from table; |
![]() | 7 fragrans23 OP @Xusually 要考虑 bus_id 对应多个 record_id 的情况,对应多个的话,record_id 只记录一次 |
![]() | 8 fragrans23 OP @zheng96 谢谢大佬,貌似可以,我得多试一下 |
![]() | 9 fragrans23 OP @sunhelter 感谢回复,mysql 好像不行 |
10 themostlazyman 2022-01-05 13:34:49 +08:00 问题描述没太懂,建议给一个最小化的表结构,再加几条典型数据来说明你的问题。 |
![]() | 11 xiangyuecn 2022-01-05 13:43:40 +08:00 “不能直接求去重后 bus_id 的数量,其他业务可能没有 bus_id” 分两条简单的 sql 语句搞定,没必要写一条蹩脚的 sql |
![]() | 12 JKeita 2022-01-05 13:59:50 +08:00 同没看懂题目 |
13 newtype0092 2022-01-05 14:10:45 +08:00 (select count(*) from table where bus_id is null) + (select count(*) from table where bus_is is not null group by bus_id) |
![]() | 14 zhuangjia 2022-01-05 14:11:55 +08:00 题目中的描述部分 “多个 bus_id 对应的 recordId 算一个数量” 有歧义,楼主在 #7 给了补充描述:“bus_id 对应的 多个 recordId 算一个数量”。 |
15 ray5173 2022-01-05 14:15:04 +08:00 select count(distinct a.record_id) from a left join b on a.record_id = b.bus_id where b.bus_id is not null |
![]() | 16 zhuangjia 2022-01-05 14:15:15 +08:00 ![]() @fragrans23 //最小化表结构: CREATE TABLE `bus_test` ( `record_id` int(11) NOT NULL AUTO_INCREMENT, `bus_id` int(11) DEFAULT '0', PRIMARY KEY (`record_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; //测试数据 INSERT INTO `test`.`bus_test` (`bus_id`) VALUES (FLOOR(RAND() * 10)); //查询 SQL select sum(case when t.bus_id is null then t.record_count else 1 end) from (SELECT count(record_id) as record_count,bus_id FROM `bus_test` group by bus_id) t; |
![]() | 17 fragrans23 OP @zhuangjia 感谢回复 |