所以,我有两个表如下: "的样品"
sample_id|measure_id|depth|date
11 | 1 | 0 |2013
17 | 1 | 1 |2013
18 | 1 | 3.5 |2013
21 | 2 | 0 |2015
22 | 2 | 1 |2015
此表包含有关现有测量样本的信息。 sample_id对于每个测量的样本都是唯一的,measure_id对于每个"测量活动都是相同的"深度和日期。
另一个表:" Sample_details ",包含有关"每个深度测量的内容的信息":
parameter_id|sample_id|value
4512 | 11 |2,45
4513 | 11 |1,58
4512 | 17 |2.11
4533 | 17 |5.36
4512 | 18 |3,45
4518 | 18 |7,52
4512 | 21 |9,21
4513 | 21 |5,12
4515 | 21 |5,12
4512 | 22 |5,12
4513 | 22 |5,12
我想要做的是将深度0的所有采样细节移动到对应于深度1的采样细节中。(我们假设总是存在深度0的样本和深度1的另一个样本)。
我试着这样说:
从样本表中获取sample_id,其中depth = 1并将sample_id中的sample_id替换为sample_id,其中sample_id等于样本表中深度为0的sample_id。(我需要为每个measure_id执行此操作,因为每个度量标识都有0深度和1个深度值,...)
我的SQL试用版:
UPDATE SDetails
SET SDetails.sample_id = Sample.sample_id
FROM Sample_details SDetails
JOIN Sample Sample
ON Sample.sample_id IN (select distinct Sample.sample_id from Sample, table2 where Sample.depth = 1 AND Sample.id2 = table2.id2)
AND SDetails.sample_id IN (select Sample.sample_id from Sample, table2 where sample.depth =0 AND Sample.id2 = table2.id2)
sample_details表应如下所示:
parameter_id|sample_id|value
4512 | 17 |2,45
4513 | 17 |1,58
4512 | 17 |2.11
4533 | 17 |5.36
4512 | 18 |3,45
4518 | 18 |7,52
4512 | 22 |9,21
4513 | 22 |5,12
4515 | 22 |5,12
4512 | 22 |5,12
4513 | 22 |5,12
答案 0 :(得分:0)
试试这个:
DECLARE @Sample TABLE(sample_id INT, measure_id INT, depth FLOAT, [date] INT)
INSERT INTO @Sample (sample_id, measure_id, depth, [date])
SELECT 11, 1, 0, 2013
UNION ALL
SELECT 17, 1, 1, 2013
UNION ALL
SELECT 18, 1, 3.5, 2013
UNION ALL
SELECT 21, 2, 0, 2015
UNION ALL
SELECT 22, 2, 1, 2015
DECLARE @sample_details TABLE (parameter_id INT, sample_id INT, value VARCHAR(50))
INSERT INTO @sample_details (parameter_id, sample_id, value)
SELECT 4512, 11, '2,45'
UNION ALL
SELECT 4513, 11, '1,58'
UNION ALL
SELECT 4512, 17, '2.11'
UNION ALL
SELECT 4533, 17, '5.36'
UNION ALL
SELECT 4512, 18, '3,45'
UNION ALL
SELECT 4518, 18, '7,52'
UNION ALL
SELECT 4512, 21, '9,21'
UNION ALL
SELECT 4513, 21, '5,12'
UNION ALL
SELECT 4515, 21, '5,12'
UNION ALL
SELECT 4512, 22, '5,12'
UNION ALL
SELECT 4513, 22, '5,12'
DECLARE @tmp TABLE (oldvalue INT, newvalue INT)
INSERT INTO @tmp(oldvalue, newvalue)
SELECT s1.sample_id, s2.sample_id
FROM @Sample s1
INNER JOIN @Sample s2 ON s2.measure_id = s1.measure_id
WHERE s1.depth = 0
AND s2.depth = 1
UPDATE sd
SET sd.sample_id = tmp.newvalue
FROM @sample_details sd
INNER JOIN @tmp tmp ON tmp.oldvalue = sd.sample_id
SELECT * FROM @sample_details
答案 1 :(得分:0)
这样的东西?
depth = 0
的所有 sample + sample_details 对。 depth = 1
示例。 depth = 1
sample_id 更新步骤1中的 sample_detail 。T-SQL:
UPDATE d
SET d.sample_id = s1.sample_id
FROM sample_details d
JOIN sample s0 ON d.sample_id = s0.sample_id
AND s0.depth = 0
JOIN sample s1 ON s0.measure_id = s1.measure_id
AND s1.depth = 1