当前位置: 代码迷 >> PB >> 求SQL语句 来吧,诸位大神们
  详细解决方案

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

热度:88   发布时间:2016-04-29 06:00:50.0
求SQL语句 来吧,各位大神们
本帖最后由 bjuwy 于 2013-07-10 17:27:36 编辑


表一是原始数据,我想通过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
  相关解决方案