在SUM函数中选择语句

时间:2015-02-25 05:28:33

标签: sql

我有两张桌子。第一个表(TableA)有一些列,如week1,week3,week4,Week7(动态)以及一些静态列,如orgno,employeeID,员工姓名。

所有动态列都存在于另一个表(TableB)中。

现在我需要进行类似的查询

SELECT OrgNo, 
SUM(SELECT ColName FROM TableB WHERE id=1), 
SUM(SELECT ColName FROM TableB WHERE id=2),
SUM(SELECT ColName FROM TableB WHERE id=3),
SUM(SELECT ColName FROM TableB WHERE id=4),
FROM TableAO
GROUP BY OrgNo

我正在使用SQL 2000。 提前谢谢。

示例:

*

TableA:*
**Orgno   EmployeeID   EmployeeName   Week1   week3   week4   Week7** 
(1         1            XX             0       5       4       3)
(1         2            YY             1       6       0       2)
(2         1            XX             0       5       4       3)
(1         3            ZZ             1       6       0       2)

*TableB:*
**ID   Name**
(1    Week1)   
(2    Week3)   
(3    Week4)   
(4    Week7)

*Desire Output:* 
**Orgno   Week1   week3   week4   Week7**    
(1        2       17       4       7)
(2        0        5       4       3)

2 个答案:

答案 0 :(得分:2)

此处无需加TABLE B,您只能通过第一张表获得所需的结果。

     SELECT 
          Orgno,
          SUM(Week1) Week1,
          SUM(Week3) Week3, 
          SUM(Week4) Week4, 
          SUM(Week7) Week7
    FROM 
          TableA 
    GROUp BY 
          Orgno

更新

从您的评论中我理解的是,您不知道第一个表的列名称,并且您希望从第二个表中获取该列名称,在这种情况下您需要使用dynamic SQL。 您可以在单个查询中获取并使用动态sql字符串连接,而不是将多个查询触发到每个列。你可以尝试这样的事情,

declare @sql  varchar(max)
set @sql = 'SELECT Orgno,' 

declare @tbl varchar(100)
set @tbl = 'tableB' -- put your table name here

SELECT @sql = @sql +'SUM(' + name + '),'
FROM tablB
WHERE Id IN(1,2,3,4) 

set @sql = LEFT(@sql, LEN(@sql) - 1)
set @sql = @sql + ' FROM ' + @tbl + ' Group BY Orgno'

EXEC (@sql)

More info on dynamic sql

答案 1 :(得分:1)

您需要构造包含SQL查询的字符串,然后使用EXEC运行它。如果您需要将它作为单个语句包装到存储过程。

查看示例here

你的案子可能会是这样的

DECLARE @sqlCommand varchar(1000)
DECLARE @column1 varchar(128)
DECLARE @column2 varchar(128)
SELECT @column1 = ColName FROM TableB WHERE id=1
SELECT @column2 = ColName FROM TableB WHERE id=2
SET @sqlCommand = 'SELECT SUM(' + @column1 + '), SUM(' + @column2 +') FROM TableAO GROUP BY OrgNo'
EXEC (@sqlCommand)