T-SQL查询 - 需要帮助

时间:2011-07-02 16:43:58

标签: sql sql-server sql-server-2005 sql-server-2008 join

我有两张桌子A和B;

Table A:
Cust_ID, Col_A, Col_B
1001, 1, 2
1002, 3, 4
1003, 2, 1
1004, 4, 3

Table B:
Col_A_Weight, Col_B_Weight
0.1111111, 0.22222

我要做的是使用T-SQL创建一个新的表C,其中

Output = Col_A*Col_A_Weight + Col_B*Col_B_Weight

表C:

Cust_ID, Output
1001, 1*0.1111111 + 2*0.22222 
1002, 3*0.1111111 + 4*0.22222
1003, 2*0.1111111 + 1*0.22222
1004, 4*0.1111111 + 3*0.22222

所以最终的表C是

Cust_ID Output
1001, 0.5555511
1002, 1.2222133
1003, 0.4444422
1004, 1.1111044

鉴于有200个Col_A,Col_B,Col_C,Col_D等以及相应的权重列,如何使用聪明的连接以便动态引用列(假设它们在两个表中对应)。由于表B没有Cust_ID字段,这使得它更加棘手。

如何做到这一点?

2 个答案:

答案 0 :(得分:2)

USE tempdb;
GO

CREATE TABLE dbo.A
(
    Cust_ID INT PRIMARY KEY,
    Col_A INT,
    Col_B INT,
    Col_C INT,
    Col_D INT,
    Col_E INT
);

INSERT dbo.A
    SELECT 1001, 1, 2, 2, 2, 2
    UNION SELECT 1002, 3, 4, 3, 3, 3
    UNION SELECT 1003, 2, 1, 5, 2, 1
    UNION SELECT 1004, 4, 3, 2, 3, 4;

CREATE TABLE dbo.B
(
    Col_A_Weight DECIMAL(10,9),
    Col_B_Weight DECIMAL(10,9),
    Col_C_Weight DECIMAL(10,9),
    Col_D_Weight DECIMAL(10,9),
    Col_E_Weight DECIMAL(10,9)
);

INSERT dbo.B
    SELECT 0.1111111, 0.22222, 0.3333, 0.444, 0.55;

DECLARE @sql NVARCHAR(MAX) = N'IF OBJECT_ID(''dbo.C'') IS NOT NULL
BEGIN
    DROP TABLE dbo.C;
END
SELECT A.Cust_ID, Output = ';

SELECT @sql += 'B.' + name + '*' 
    + REPLACE(name, '_Weight', '') + ' + '
FROM sys.columns 
WHERE [object_id] = OBJECT_ID('dbo.B');

SELECT @sql = LEFT(@sql, LEN(@sql)-2)
    + ' INTO dbo.C
        FROM dbo.A AS A
        CROSS JOIN dbo.B AS B;';

EXEC sp_executeSQL @sql;

SELECT * FROM dbo.C;

GO
DROP TABLE dbo.A, dbo.B;

答案 1 :(得分:0)

我相信您正在寻找交叉联接,例如

Select 
CustID,
TableA.Col_A*TableB.Col_A_Weight +
TableA.Col_B*TableB.Col_B_Weight +
TableA.Col_C*TableB.Col_C_Weight
From TableA
Cross Join TableB