请看表T1编号 名称 价格 分类 控制 时间
1 A 10 C1 不 2010-9-1
2 B 10 C1 是 2010-8-12
3 D 10 C2 是 2010-7-13
4 H 10 C3 是 2010-5-18想要的结果共有记录 受控的 九月份 总价
4 3 1 40
1 A 10 C1 不 2010-9-1
2 B 10 C1 是 2010-8-12
3 D 10 C2 是 2010-7-13
4 H 10 C3 是 2010-5-18想要的结果共有记录 受控的 九月份 总价
4 3 1 40
count(1) as 共有记录,
sum(case 控制 when '是' then 1 else 0 end) as 受控的,
sum(case when datepart(mm, 时间)=9 then 1 else 0 end) as 九月份,
sum(价格)
from
tb
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-10-10 10:17:42
-- Verstion:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([编号] int,[名称] varchar(1),[价格] int,[分类] varchar(2),[控制] varchar(2),[时间] datetime)
insert [tb]
select 1,'A',10,'C1','不','2010-9-1' union all
select 2,'B',10,'C1','是','2010-8-12' union all
select 3,'D',10,'C2','是','2010-7-13' union all
select 4,'H',10,'C3','是','2010-5-18'
--------------开始查询--------------------------
select
count(1) as 共有记录,
sum(case 控制 when '是' then 1 else 0 end) as 受控的,
sum(case when datepart(mm, 时间)=9 then 1 else 0 end) as 九月份,
sum(价格)
from
tb
----------------结果----------------------------
/* 共有记录 受控的 九月份
----------- ----------- ----------- -----------
4 3 1 40(1 行受影响)*/
if object_id('tb','U') is not null
drop table tb
go
create table tb
(
编号 int identity(1,1) not null,
名称 varchar(10) not null,
价格 int not null,
分类 varchar(10) not null,
控制 varchar(10) not null,
时间 datetime not null
)
go
insert into tb (名称,价格,分类,控制,时间)
select 'A',10,'C1','不','2010-9-1' union all
select 'B',10,'C1','是','2010-8-12' union all
select 'D',10,'C2','是','2010-7-13' union all
select 'H',10,'C3','是','2010-5-18'
GO
SELECT 共有记录=(select count(*) from tb),
受控的=(select count(*) from tb where 控制='是'),
九月份=(select count(*) from tb where MONTH(时间)=9),
总价=(select sum(价格) from tb)
GO