如何计算不同的行并获取行的数据和计数作为第二列

时间:2015-08-20 13:00:14

标签: sql

假设我有一个数据

ID
AAA
ABB
ABC
BDS
BRD
CXD
DCU
ETS

我想要计算第一个字母的行,并将它们的外观数量设为右边。对不起我知道我不是一个技术语言的好用户,但我是SQL新手,英语不是我的第一语言。 所以通过脚本我想返回

ID  Total
A  3
B  2
C  1
D  1
E  1

我试过了

select left(id,1), count(left(id,1) as Total 
from Places 
group by Id 
order by Total desc;

,但没有用。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

select left(id,1), count(*) as Total 
from Places 
group by left(id,1)
order by Total desc;

答案 1 :(得分:0)

这是你需要的吗?

declare @t table(val varchar(10))
insert into @t
select 'AAA' union all 
select 'ABB' union all 
select 'ABC' union all 
select 'BDS' union all 
select 'BRD' union all 
select 'CXD' union all 
select 'DCU' union all 
select 'ETS'
select left(t1.val,1) as id ,count(t1.val) as total from @t as t1 left join
(
select distinct right(val,1) as val  from @t 
) as t2 on t1.val =t2.val
  group by left(t1.val,1)

结果是

id   total
---- -----------
A    3
B    2
C    1
D    1
E    1