具有硬编码列名称的SQL更新

时间:2015-12-20 15:30:39

标签: sql sql-server

我需要帮助为以下示例创建SQL更新(包含示例数据):

表1:DETAILTRAN 结构:供应商CHAR(10),员工CHAR(10),WEEK INT

VENDOR   EMPLOYEE      WEEK
VEN01       EMP01         1
VEN01       EMP01         1
VEN02       EMP03         1
VEN03       EMP02         1
VEN01       EMP01         2
VEN01       EMP01         2
VEN01       EMP03         2
VEN03       EMP02         2
VEN02       EMP01         3
VEN02       EMP01         3
VEN02       EMP03         3
VEN03       EMP03         3

表2:SUMMARTRAN(需要更新)

结构:WEEK01 INT,WEEK02 INT,WEEK03 INT,供应商CHAR(10),EMPLOYEE CHAR(10) SQL Update此表(SUMMARTRAN)的结果应如下所示:

WEEK01     WEEK02    WEEK03    VENDOR   EMPLOYEE
2          3         0         VEN01
1          0         3         VEN02
1          1         1         VEN03
2          2         2                  EMP01
1          1         0                  EMP02
1          1         2                  EMP03

2 个答案:

答案 0 :(得分:2)

您可以使用grouping sets和条件聚合:

来解决此问题
select vendor, employee,
       sum(case when week = 1 then 1 else 0 end) as week01,
       sum(case when week = 2 then 1 else 0 end) as week02,
       sum(case when week = 3 then 1 else 0 end) as week03
from DETAILTRAN
group by grouping sets ((vendor), (employee));

您可以将其合并到insert的{​​{1}}声明中:

summartran

答案 1 :(得分:1)

试试这个

with VENDOR as
(
select isnull(count(case when WEEK = 1 then WEEK end),0) WEEK01,
       isnull(count(case when WEEK = 2 then WEEK end),0) WEEK02 ,  
       isnull(count(case when WEEK = 3 then WEEK end),0) WEEK03 ,
VENDOR
from DETAILTRAN 
group by VENDOR
),EMPLOYEE as
(
select isnull(count(case when WEEK = 1 then WEEK end),0) WEEK01,
       isnull(count(case when WEEK = 2 then WEEK end),0) WEEK02 ,  
       isnull(count(case when WEEK = 3 then WEEK end),0) WEEK03 ,
EMPLOYEE
from DETAILTRAN 
group by EMPLOYEE
)
select WEEK01, WEEK02, WEEK03, VENDOR, EMPLOYEE = '' from VENDOR 
union all
select WEEK01, WEEK02, WEEK03, VENDOR='', EMPLOYEE from EMPLOYEE

要将结果更新为SUMMARTRAN表,请使用此

with VENDOR as
(
select isnull(count(case when WEEK = 1 then WEEK end),0) WEEK01,
       isnull(count(case when WEEK = 2 then WEEK end),0) WEEK02 ,  
       isnull(count(case when WEEK = 3 then WEEK end),0) WEEK03 ,
VENDOR
from DETAILTRAN 
group by VENDOR
),EMPLOYEE as
(
select isnull(count(case when WEEK = 1 then WEEK end),0) WEEK01,
       isnull(count(case when WEEK = 2 then WEEK end),0) WEEK02 ,  
       isnull(count(case when WEEK = 3 then WEEK end),0) WEEK03 ,
EMPLOYEE
from DETAILTRAN 
group by EMPLOYEE
)
insert into  SUMMARTRAN (WEEK01, WEEK02, WEEK03, VENDOR, EMPLOYEE)
select WEEK01, WEEK02, WEEK03, VENDOR, EMPLOYEE = '' from VENDOR 
union all
select WEEK01, WEEK02, WEEK03, VENDOR='', EMPLOYEE from EMPLOYEE