今天发现很多东西都遗忘了,写几个简单的sql熟悉下:
表 T_TestDistinctAndGroupBy
a | b |
---|---|
1 | A |
2 | A |
3 | B |
4 | C |
5 | B |
在w3c的基础介绍自己可以翻阅看下
--1. distinct作用于a,b,而不是只作用在a上,此情况下 distinct必须放在最前面
select distinct a,b from T_TestDistinctAndGroupBy
a b
-------------------------------------------------- --------------------------------------------------
1 A
2 A
3 B
4 C
5 B
(5 行受影响)
--2. distinct只可以放在最前面,也可以放在count(distinct)
select a,COUNT(distinct b) from T_TestDistinctAndGroupBy group by a
a
-------------------------------------------------- -----------
1 1
2 1
3 1
4 1
5 1
(5 行受影响)
--3. 可以单独使用聚合函数,也可以单独使用group by,但在下面情况,使用了聚合函数,必须要使用group by,必须要将所有字段包含在group by内
select *,COUNT(distinct b) from T_TestDistinctAndGroupBy group by a,b
a b
-------------------------------------------------- -------------------------------------------------- -----------
1 A 1
2 A 1
3 B 1
5 B 1
4 C 1
(5 行受影响)
若有问题,请指正。