今天朋友老劉突然用Skype送了一段ORACLE的SQL語法來,語法最下面是 Having Count(1) = XXXXX,寫SQL語法也寫了五、六年了,Count(1)倒是第一次看到,當下就趕緊問一下Google先生,怪怪...,想不到Group by 後還可以 Count(1) 這種寫法來抓重覆資料筆數,我開啟我那可愛的 SSMSE 來試試 SQL SERVER是不是也可以用這個語法,下面為我測試的內容:
Create table #a
(
A char(1),
B char(1)
)
(
A char(1),
B char(1)
)
Insert Into #a
values('1','2')
Insert Into #a
values('1','2')
Insert Into #a
values('2','2')
Insert Into #a
values('3','1')
Insert Into #a
values('1','1')
Insert Into #a
values('4','4')
Insert Into #a
values('4','1')
Insert Into #a
values('2','2')
values('1','2')
Insert Into #a
values('1','2')
Insert Into #a
values('2','2')
Insert Into #a
values('3','1')
Insert Into #a
values('1','1')
Insert Into #a
values('4','4')
Insert Into #a
values('4','1')
Insert Into #a
values('2','2')
Select a,b,rows = count(1) from #a group by a,b
a b rows
---- ---- -----------
1 1 1
3 1 1
4 1 1
1 2 2
2 2 2
4 4 1
a b rows
---- ---- -----------
1 1 1
3 1 1
4 1 1
1 2 2
2 2 2
4 4 1
Select a,b,rows = count(1) from #a group by a,b
having count(1) > 1
a b rows
---- ---- -----------
1 2 2
2 2 2
having count(1) > 1
a b rows
---- ---- -----------
1 2 2
2 2 2
Select a,b from #a group by a,b
having count(1) > 1
a b
---- ----
1 2
2 2
having count(1) > 1
a b
---- ----
1 2
2 2
使用這種語法可以很簡單得知每個群組筆數,不用再建Temp Table了 ~~
沒有留言:
張貼留言