求SQL语句,SQL高手进来,100分哦~

来源:百度知道 编辑:UC知道 时间:2024/09/26 13:15:38
数据库中有一张表T,有三个字段,A,year(年份),C,其中A字段只有a1,a2,a3三个数值,year是代表不同年份,C字段是一些其他数据
要求:写一段SQL语句,查询出一张2维表,分别求出每年年a1,a2,a3的对应数量
就像这样
----|-a1-|-a2-|a3
2008|-10-|-20-|30
2009|-20-|-24-|34
用的是SQL server.. 2000...
注意A字段是要被统计的,要使用到count(*) where A = 'a1'类似这样的,不是简单的select
我是不想在程序里每个单元格都写一个count(*)语句,所以想直接弄在SQL语句里

用行列转置函数pivot来做

下面的语句你试试,应该没问题

select [year],a1,a2,a3 FROM (select [year],A,C from T)p pivot(sum(C) for A in (a1,a2,a3 )) as pvt order by [year]

有问题hi我

2000.....

这次对了吧,你再试试,瓦咔咔

select [year],
count(case A when a1 then 1 else null end) as a1,
count(case A when a2 then 1 else null end) as a2,
count(case A when a3 then 1 else null end) as a3
from T WHERE A IN(a1,a2,a3) group by [year]

这样试试:

select year,
sum(case A when 'A1' then 1 else 0 end) A1,
sum(case A when 'A2' then 1 else 0 end) A2,
sum(case A when 'A3' then 1 else 0 end) A3
from [表名]
group by year

select year,
sum(case when A='A1' then 1 else 0 end) A1,
sum(case when A='A2' then 1 else 0 end) A2,
sum(case when A='A3' then 1 else 0 end) A3
from [表名]
group by year
就可以了.

以 year 加字段A 的值 作为字段,创建一个临时表#tmp,