创建表:
CREATE TABLE tst11 (
`money` bigint DEFAULT NULL COMMENT '组织ID',
`org` varchar(32) DEFAULT NULL COMMENT '组织名称'
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='test';
写入数据后,表如下
money | org |
100 | 部门1 |
15 | 部门1 |
15 | 部门1 |
2000 | 部门2 |
以部门和金额维度重复的数据只取其中一条: select distinct org,money from tst11;
org | money |
部门1 | 100 |
部门1 | 15 |
部门2 | 2000 |
单部门维度:select distinct org from tst11;
org |
部门1 |
部门2 |
如果要以distinct维度统计条数,语法只能是select count(distinct org,money) from tst11;
distinct的统计维度在他之后,如果在distinct后接count或者sum,统计出来的数据只会有一条,对比group by 统计维度也在他之后,不过可以搜索出多个维度的count或者sum
部门维度:select sum(money),org from tst11 group by org;
`sum(money)` | org |
130 | 部门1 |
2000 | 部门2 |
部门&金额维度:select sum(money),org from tst11 group by org,money;
`sum(money)` | org |
100 | 部门1 |
30 | 部门1 |
2000 | 部门2 |
原本distinct和group by是没有可比性的,最直观的区别
select count(distinct org) from tst11;
select count(*) from tst11 group by org;
第一个搜出来的结果是2,第二个搜出来的结果是3,1
根本原因是distinct对于重复数据只取出一条,而group by是将org归类,然后分别count