SQL小问题
得到:
ID 产品ID 时间 v1 v2 v3 v4 sums
1 1001 17:10 0 0 0 0 0
2 1002 17:20 1 0 1 0 2
3 1003 17:30 0 1 0 0 1
4 1004 17:40 0 0 1 0 1
5 1005 17:50 0 1 0 0 0
sums 5 1 2 2 0 AA
AA=3,如果AA是sums!=0的和,怎么做??
------解决方案--------------------create table T(ID int, 产品ID char(4), 时间 char(5), v1 int, v2 int, v3 int, v4 int, sums int)
insert T select 1, '1001 ', '17:10 ', 0, 0, 0, 0, 0
union all select 2, '1002 ', '17:20 ', 1, 0, 1, 0, 2
union all select 3, '1003 ', '17:30 ', 0, 1, 0, 0, 1
union all select 4, '1004 ', '17:40 ', 0, 0, 1, 0, 1
union all select 5, '1005 ', '17:50 ', 0, 1, 0, 0, 1
select ID=rtrim(ID), 产品ID, ' ' 时间, rtrim(v1), rtrim(v2), rtrim(v3), rtrim(v4), rtrim(sums) sums from T
union all
select 'sums ', count(*), ' ', rtrim(sum(v1)), rtrim(sum(v2)), rtrim(sum(v3)), rtrim(sum(v4)), 'AA ' sums from T
------解决方案--------------------select id=sums,产品ID=count(产品ID), 时间= ' ',v1=sum(v1),v2 =sum(v2),v3=sum(v3),v4 =sum(v4), sums=sum(sums) from tablename
------解决方案--------------------select id=sums,产品ID=count(产品ID), 时间= ' ',v1=sum(v1),v2 =sum(v2),v3=sum(v3),v4 =sum(v4), sums=sum(case when sums <> 0 then 1 else 0 end) from tablename
------解决方案--------------------sum(case sums when 0 then 0 else 1 end) as AA
------解决方案--------------------select ID=rtrim(ID), 产品ID,时间, rtrim(v1), rtrim(v2), rtrim(v3), rtrim(v4), rtrim(sums) sums from #t
union all
select 'sums ', count(*), ' ', rtrim(sum(v1)), rtrim(sum(v2)), rtrim(sum(v3))