读书人

sql查询语句的有关问题

发布时间: 2012-01-22 22:38:43 作者: rapoo

sql查询语句的问题
比如说有这样一个表
ID SType
30 1
30 1
30 2
30 1

如何返回两种Stype的总数呢?

ID SType1 SType2
30 3 1

谢谢

[解决办法]
select (select ID,count(*) as SType1 from 表 where Stype=1 group by ID),
(select count(*) as SType2 from 表 where Stype=2)

[解决办法]

SQL code
select id,sum(case SType when 1 then 1 end)) as SType1,sum(case SType when 2 then 1 end)) as SType2from 这样一个表group by id
[解决办法]
select s.ID,s.SType1,t.SType2
from (select ID,count(*) as SType1 from 表 where Stype=1 group by ID) s inner join
(select ID,count(*) as SType2 from 表 where Stype=2 group by ID) t
on s.ID=t.ID
[解决办法]

这是一个典型的交叉表查询问题。

TRANSFORM Count(SType) AS SType之计数
SELECT id
FROM 表
GROUP BY id
PIVOT SType;


读书人网 >VB

热点推荐