导入的Excel工作表到SQL server.i选择了一个表。在此表中有很多行值。在这个行中,单个员工多次来到这个表。我希望此COlumn中的单个Employee应该具有重复列中的所有值。我将展示样本数据以供参考。
Name E1 E2 E3 E4 E5
Jeni 1 0 0 0 0
Jeni 0 0 2 0 0
Jeni 0 5 0 0 3
Priya 0 3 0 0 0
Priya 0 0 0 0 3
Priya 0 0 7 0 0
Priya 10 0 0 0 0
我的表看起来像选择表后我的结果应该是
Name E1 E2 E3 E4 E5 Total
jeni 1 5 2 0 3 11
Priya 10 3 7 0 3 23
我希望是这样的。我希望解释清楚一点。请问如何实现这一点。请参考BEST TUTORIAL学习SQL很短的时间。谢谢你的进步。我希望Wil能帮到你。我是新的SQL Server。
答案 0 :(得分:5)
CREATE TABLE #Table1
([Name] varchar(5), [E1] int, [E2] int, [E3] int, [E4] int, [E5] int)
;
INSERT INTO #Table1
([Name], [E1], [E2], [E3], [E4], [E5])
VALUES
('Jeni', 1, 0, 0, 0, 0),
('Jeni', 0, 0, 2, 0, 0),
('Jeni', 0, 5, 0, 0, 3),
('Priya', 0, 3, 0, 0, 0),
('Priya', 0, 0, 0, 0, 3),
('Priya', 0, 0, 7, 0, 0),
('Priya', 10, 0, 0, 0, 0)
;
SELECT *,A.E1+A.E2+A.E3+A.E4+A.E5 AS 'TOTAL' FROM ( SELECT NAME, SUM(E1) E1 ,SUM(E2) E2 ,SUM(E3) E3 ,SUM(E4) E4 ,SUM(E5) E5 FROM #TABLE1 GROUP BY NAME)A
输出
NAME E1 E2 E3 E4 E5 TOTAL
Jeni 1 5 2 0 3 11
Priya 10 3 7 0 3 23
答案 1 :(得分:3)
你要找的东西是Group by。
要获得您正在寻找的结果,我只是制作了您描述的表格,然后对整数值进行了总结。
select name, sum(E1),sum(E2),sum(E3),sum(E4),sum(E5) from Test Group by name
答案 2 :(得分:0)
;With cte(Name,E1,E2,E3,E4,E5)
AS
(
SELECT 'Jeni' ,1 ,0 , 0, 0, 0 Union all
SELECT 'Jeni' ,0 ,0 , 2, 0, 0 Union all
SELECT 'Jeni' ,0 ,5 , 0, 0, 3 Union all
SELECT 'Priya',0 ,3 , 0, 0, 0 Union all
SELECT 'Priya',0 ,0 , 0, 0, 3 Union all
SELECT 'Priya',0 ,0 , 7, 0, 0 Union all
SELECT 'Priya',10,0 , 0, 0, 0
)
SELECT Name,E1,E2,E3,E4,E5,Total FROM
(
SELECT *,Row_number()Over(Partition by Name order by Name)AS Seq From
(
SELECT Name,SUM(E1)E1,
SUM(E2)E2,
SUM(E3)E3,
SUM(E4)E4,
SUM(E5)E5,
SUM(E1+E2+ E3+ E4+E5) AS Total
FROM cte
Group by Name
)Dt
)AS Final
WHERE Final.Seq=1