很抱歉,标题令人困惑。从2表中选择时出现问题。我有2张桌子。
表1:包含表2的列名
+ Pkey | name1 | name2 +
+----------------------+
| 1 | a | b |
+----------------------+
| 2 | c | b |
表2:包含值
+ Pkey | a | b | c +
+----------------------+------+
| 1 | 10 | 2 | 7 |
+----------------------+------+
| 2 | 12 | 4 | 8 |
+----------------------+------+
| 3 | 8 | 2 | 4 |
+----------------------+------+
| 4 | 7 | 1 | 3 |
我想从表2中获取最大值(值),并在选择表1时添加 示例:表1的第一行包含2个值:a和b。从这两个值,我们参考表2来计算列a-列b为[8,8,6,6]。得到此列的最大值后为8,并在查询表1时添加。继续下一行
所需表:
+ Pkey | name1 | name2 | Desired column |
+----------------------+-------------------+
| 1 | a | b | 8 |
+----------------------+-------------------+
| 2 | c | b | 5 |
表1中有超过10000行。我使用过函数,但在Function中不能使用动态
答案 0 :(得分:1)
一种可能的方法是生成动态SQL:
-- Tables
CREATE TABLE #Table1 (
Pkey int,
name1 varchar(1),
name2 varchar(1)
)
INSERT INTO #Table1 (Pkey, name1, name2)
VALUES
(1, 'a', 'b'),
(2, 'c', 'b')
CREATE TABLE #Table2 (
Pkey int,
a int,
b int,
c int
)
INSERT INTO #Table2 (Pkey, a,b, c)
VALUES
(1, 10, 2, 7),
(2, 12, 4, 8),
(3, 8, 2, 4),
(4, 7, 1, 3)
-- Statement
DECLARE @stm nvarchar(max)
SET @stm = N''
SELECT @stm = @stm +
N'UNION ALL
SELECT
' + STR(Pkey) + ' AS Pkey,
''' + name1 + ''' AS name1,
''' + name2 + ''' AS name2, ' +
'PkeyMax = (SELECT MAX(' + name1 + ' - ' + name2 + ') FROM #Table2) '
FROM #Table1
SELECT @stm = STUFF(@stm, 1, 10, '')
-- Execution
EXEC (@stm)
输出:
Pkey name1 name2 PkeyMax
1 a b 8
2 c b 5
答案 1 :(得分:0)
由于字段很少,因此可以使用CASE来获取所需的结果,从而获得所需的结果(以避免构建动态SQL)
SELECT pkey,name1,name2,max(dif) FROM
(SELECT t1.pkey, t1.name1, t1.name2,
case when t1.name1 ='a' then t2.a
when t1.name1 ='b' then t2.b
when t1.name1 ='c' then t2.c
end
-
case when t1.name2 ='a' then t2.a
when t1.name2 ='b' then t2.b
when t1.name2 ='c' then t2.c
end dif
FROM Table1 t1 , Table2 t2) IQ
GROUP BY IQ.pkey, IQ.name1, IQ.name2