读书人

求SQL话语 来吧各位大神们

发布时间: 2013-07-16 22:38:05 作者: rapoo

求SQL语句 来吧,各位大神们


表一是原始数据,我想通过SQL语句计算再插入到表二,达到表二中这样的效果,求SQL语句,游标也行
来吧,各位大神们 我知道你们都很厉害

[解决办法]


declare @t table (片区 nvarchar(20), 数量 int, 金额 money)
Insert into @t(片区, 数量, 金额)
select '重庆', 1, 234 union all
select '重庆', 2, 23 union all
select '重庆', 1, 42 union all
select '重庆', 2, 342 union all
select '重庆', 3, 4 union all
select '重庆', 4, 234 union all
select '重庆', 1, 23 union all
select '重庆', 2, 42

select * from @t

select 片区, count(case 数量 when 1 then 1 else 2 end) as 数量, sum(金额) as 金额
from @t
group by 片区,case 数量 when 1 then 1 else 2 end

--结果

(8 行受影响)
片区 数量 金额
-------------------- ----------- ---------------------
重庆 1 234.00
重庆 2 23.00
重庆 1 42.00
重庆 2 342.00
重庆 3 4.00
重庆 4 234.00


重庆 1 23.00
重庆 2 42.00

(8 行受影响)

片区 数量 金额
-------------------- ----------- ---------------------
重庆 3 299.00
重庆 5 645.00

(2 行受影响)

--数量非1 的行合计金额是 645 不是546(如果这种方法是正确的话!)




[解决办法]


表一是原始数据,我想通过SQL语句计算再插入到表二,达到表二中这样的效果,求SQL语句,游标也行
来吧,各位大神们 我知道你们都很厉害


select 片区, count(1), sum(数量)
from table
where 数量 = 1
union all
select 片区, count(1), sum(数量)
from table
where 数量 > 1

读书人网 >PB

热点推荐