问题描述:表a1和表a2的表结构相同。说明:一个单位有多种税,同一单位在表a1中出现的tax不会在a2出现(例:表a1中单位1的税1和税2在表a2的单位1里不会出现)
表1:a1
ID Unit tax price date
1 单位1 税1 2 2009-3-1
2 单位1 税2 4 2009-3-1
3 单位2 税2 15 2009-3-1
4 单位2 税3 15 2009-3-1
5 单位3 税1 22 2009-3-1表2:a1
ID Unit tax price date
1 单位1 税3 5 2009-3-1
2 单位1 税4 6 2009-3-1
3 单位2 税1 7 2009-3-1
4 单位3 税3 13 2009-3-1
5 单位4 税5 18 2009-3-1要求得到以下结果:
1.得到2008年3月份各单位下纳税总和的排名。
Unit price
单位2 37
单位3 35
单位4 18
单位1 17
2.得到2008年3月份各单位指定税金(显示税金1,税金3)的总和。
Unit 税金1 税金3 税金总和
单位1 2 5 7
单位2 7 15 22
单位3 22 13 35
单位4 无 无 无
表1:a1
ID Unit tax price date
1 单位1 税1 2 2009-3-1
2 单位1 税2 4 2009-3-1
3 单位2 税2 15 2009-3-1
4 单位2 税3 15 2009-3-1
5 单位3 税1 22 2009-3-1表2:a1
ID Unit tax price date
1 单位1 税3 5 2009-3-1
2 单位1 税4 6 2009-3-1
3 单位2 税1 7 2009-3-1
4 单位3 税3 13 2009-3-1
5 单位4 税5 18 2009-3-1要求得到以下结果:
1.得到2008年3月份各单位下纳税总和的排名。
Unit price
单位2 37
单位3 35
单位4 18
单位1 17
2.得到2008年3月份各单位指定税金(显示税金1,税金3)的总和。
Unit 税金1 税金3 税金总和
单位1 2 5 7
单位2 7 15 22
单位3 22 13 35
单位4 无 无 无
解决方案 »
- 求一个sql?---万分感谢!
- SQL Server的查询速度会不会随着表中数据量的增大而变慢?
- 用PowerDesigner设计数据库物理图,包括多个对象,如表(Table)、字段(Column)、域(Domain)
- 行变字符串
- 这个网站用Sqlserver写的吗?
- 怎么在SQL中循环插入1000条记录?
- sql语句的一个时间转换问题!
- 也求一条sql语句
- 求一解,我想取一个字符字段里除了前两位剩下的字符,用什么函数啊,我找不到?
- 关于VB6中的ADO采集数据出错的问题!急!急!急!!!!!!
- SQLServer错误的处理
- 我公司sql server 2005有150个表,请问如何得到各个表的记录总数?
select Unit,sum(price) as price
from
(
select * from [表1] union all select * from [表2]
) t
group by Unit
order by price desc
/**
Unit price
----- -----------
单位2 37
单位3 35
单位4 18
单位1 17(所影响的行数为 4 行)
**/
(
select Unit , sum(price) price from a1 where convert(varchar(7),date,120) = '2009-03'
) n where n.price > m.price
) + 1 from
(
select Unit , sum(price) price from a1 where convert(varchar(7),date,120) = '2009-03'
) m
select
Unit,
sum(case [tax] when '税1' then price else 0 end) as 税金1,
sum(case [tax] when '税3' then price else 0 end) as 税金1,
sum(case when [tax] in('税1','税3') then price else 0 end) as 税金总和
from
(
select * from [表1] union all select * from [表2]
) t
group by Unit/**
Unit 税金1 税金1 税金总和
----- ----------- ----------- -----------
单位1 2 5 7
单位2 7 15 22
单位3 22 13 35
单位4 0 0 0(所影响的行数为 4 行)
**/
sum(case tax when '税1' then price else 0 end) [税金1],
sum(case tax when '税3' then price else 0 end) [税金3],
isnull((select sum(price) from a1 when tax in ('税1' , '税3') and Unit = t.Unit),0) [税金总和]
from a1 t
group by unit