读书人

请教这样的SQL Server查询可以实现吗

发布时间: 2012-09-06 10:37:01 作者: rapoo

请问这样的SQL Server查询可以实现吗?
有这样一个表:

日期 品种 价格
2012/1/1 a 8
2012/1/1 b 7
2012/1/1 c 11
2012/1/1 d 12
2012/1/1 e 9
2012/1/1 f 10
2012/1/1 g 13
2012/1/2 a 11
2012/1/2 b 9
2012/1/2 c 8
2012/1/2 d 7
2012/1/2 e 10
2012/1/2 f 11
2012/1/3 a 10
2012/1/3 b 11
2012/1/3 c 9
2012/1/3 d 11
2012/1/3 e 12
2012/1/3 f 8
2012/1/3 g 7
2012/1/3 h 9
2012/1/3 i 10
2012/1/3 j 12
2012/1/3 k 8
希望经过查询后得到这样的一个结果:

日期 品种数 大于等于10元品种数

2012/1/1 7 4

2012/1/2 6 3

2012/1/3 11 6


对第一个表按日期汇总,得到每一天里品种的总数,和大于等于10元品种的个数。


[解决办法]

SQL code
select 日期,count(*) as 品种数,    sum(case when 价格 >= 10 then 1 else 0 end) as 大于等于10品种数from tbgroup by 日期
[解决办法]
SQL code
--> 测试数据:@Tdeclare @T table([日期] datetime,[品种] varchar(1),[价格] int)insert @Tselect '2012/1/1','a',8 union allselect '2012/1/1','b',7 union allselect '2012/1/1','c',11 union allselect '2012/1/1','d',12 union allselect '2012/1/1','e',9 union allselect '2012/1/1','f',10 union allselect '2012/1/1','g',13 union allselect '2012/1/2','a',11 union allselect '2012/1/2','b',9 union allselect '2012/1/2','c',8 union allselect '2012/1/2','d',7 union allselect '2012/1/2','e',10 union allselect '2012/1/2','f',11 union allselect '2012/1/3','a',10 union allselect '2012/1/3','b',11 union allselect '2012/1/3','c',9 union allselect '2012/1/3','d',11 union allselect '2012/1/3','e',12 union allselect '2012/1/3','f',8 union allselect '2012/1/3','g',7 union allselect '2012/1/3','h',9 union allselect '2012/1/3','i',10 union allselect '2012/1/3','j',12 union allselect '2012/1/3','k',8select     日期,    count(1) as 品种数,    sum(case when 价格>10 then 1 else 0 end) as 大于等于10元品种数from @T group by 日期/*日期                      品种数         大于等于10元品种数----------------------- ----------- -----------2012-01-01 00:00:00.000 7           32012-01-02 00:00:00.000 6           22012-01-03 00:00:00.000 11          4*/ 

读书人网 >SQL Server

热点推荐