繁体   English   中英

count(*)+ group by + having

[英]count(*)+group by+having

CREATE TABLE IF NOT EXISTS `un_tr` (
  `ut_id` int(11) NOT NULL AUTO_INCREMENT,
  `date` date DEFAULT NULL,
  `s_p_c` double NOT NULL,
  `d_c` double NOT NULL,
  `tr_id` int(11) DEFAULT NULL,
  `ev_t` varchar(50) DEFAULT NULL,

  PRIMARY KEY (`ut_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;


INSERT INTO `un_tr` (`ut_id`, `date`, 
`s_p_c`, `d_c`, `tr_id`, `ev_type`) VALUES
(1, '2018-06-01', 20.33333, 21.33333, 1, 'accident', NULL),
(2, '2018-07-02', 21.33333, 23.33333, 1, 'accident', NULL),
(3, '2018-06-03', 21.33333, 24.33333, 1, 'accident', NULL),
(4, '2018-06-04', 25.33333, 26.33333, 1, 'travel', NULL),
(5, '2018-06-04', 21.33333, 26.33333, 2, 'travel', NULL),
(6, '2018-06-04', 21.33333, 26.33333, 2, 'accident', NULL),
(7, '2018-06-04', 21.33333, 26.33333, 2, 'travel', NULL),
(8, '2018-06-04', 21.33333, 26.33333, 3, 'travel', NULL),
(9, '2018-08-04', 19.33333, 26.33333, 4, 'travel', NULL);

我只需要一个记录计数(ut.tr_id)

select  count(distinct ut.tr_id) as count_tr from un_tr ut group  by ut.tr_id having count(ut.ut_id)>1

但我得到了结果:

count_tr
1
1

我想得到结果:

count_tr
2

你想给我建议吗,我该怎么做? 谢谢。

你查询

select  count(distinct ut.tr_id) as count_tr 
from un_tr ut 
group  by ut.tr_id 
having count(ut.ut_id)>1

可以简化为

select  ut.tr_id
from un_tr ut 
group  by ut.tr_id 
having count(ut.ut_id)>1

因为没有必要进行count(distinct ut.tr_id)group by ut.tr_id的结果是这个计数总是ut.tr_id 1。

您现在可以通过以下方式计算不同tr_id事件的数量:

select count(*)
from
(
   select  ut.tr_id
   from un_tr ut 
   group  by ut.tr_id 
   having count(ut.ut_id)>1

) as t

你可以尝试这个查询:

select count(*) as count_tr from (
   select distinct tr_id as dtr_id, count(ut_id)
   from un_tr 
   group by dtr_id
   having count(ut_id) > 1
  ) a;

结果:

+----------+
| count_tr |
+----------+
|        2 |
+----------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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