假如有三种纸张种类 A3 、 A4 、 A5 ,三个工人 张、 李、 王 每次作业用的种类可能都不一样,查询要怎样写才能得到正确的统计结果最后结果反映在 DataGrid 里 总纸张数(不分种类)
张李王数据库数据A3使用人 纸张数 A4使用人 纸张数 A5使用人 纸张数张 1 王 3 李 4王 2 李 1张 4
SUM里面的条件不知道应该怎么写才对
张李王数据库数据A3使用人 纸张数 A4使用人 纸张数 A5使用人 纸张数张 1 王 3 李 4王 2 李 1张 4
SUM里面的条件不知道应该怎么写才对
select 使用人,sum(数量) from
(select A3使用人 as 使用人,数量1 as 数量 from #A
union all
select A4使用人 as 使用人,数量2 as 数量 from #A
union all
select A5使用人 as 使用人,数量3 as 数量 from #A
) a
where 使用人 is not null
group by 使用人
表二 userid userName这样查比较容易
--测试数据
declare @table table (A3使用人 nvarchar(10),A3纸张数 int,A4使用人 nvarchar(10),A4纸张数 int,
A5使用人 nvarchar(10),A5纸张数 int)
insert into @table
select '张',1,'王',3,'李',4 union all
select '王',2,'李',1,'',null union all
select '张',4,'',null,'',null
--只能做成存储过程了,以姓名来查询
declare @name nvarchar(10)
set @name = '张'
select @name as 使用人,sum(case A3使用人 when @name then (isnull(A3纸张数,0)) else 0 end +
case A4使用人 when @name then (isnull(A4纸张数,0)) else 0 end +
case A5使用人 when @name then (isnull(A5纸张数,0)) else 0 end) as 总纸张数
from @table
--结果
--------------
张 5