将来自可变数量的数据集的数据合并为一个

时间:2016-08-25 14:08:19

标签: sql sql-server

我有两个查询返回相同数量的c_id s(金额可变)

SELECT c_id FROM test WHERE test_id=123 AND op=1

SELECT c_id FROM test WHERE test_id=123 AND op=2

示例:

第一个查询返回1,3,5,7

第二个查询返回2,4,6,8

相应的ID是:

1 2
3 4
5 6
7 8

使用这些c_id我想使用此查询:

SELECT a.offset, a.values, b.value
FROM data AS a INNER JOIN data AS b  ON a.offset=b.offset
AND a.c_id=RESULTS FROM FIRST QUERY ABOVE
AND b.c_id=RESULTS FROM SECOND QUERY ABOVE

我的预期结果应如下所示:

offset where c_id=1    Data where c_id=1     Data where c_id=2
.
.
.
offset where c_id=3    Data where c_id=3     Data where c_id=4
.
.
offset where c_id=5    Data where c_id=5     Data where c_id=6
.
.
.
.
offset where c_id=7    Data where c_id=7     Data where c_id=8
.
.
.
.
.

相应的c_id s返回的数据量相等

我怎样才能实现这一目标?它就像一个UNION ALL,包含所有c_id个,但我不知道该怎么做......

1 个答案:

答案 0 :(得分:0)

听起来你需要一个:

SELECT a.offset, a.values, b.value
FROM data AS a INNER JOIN data AS b  ON a.offset=b.offset
AND a.c_id IN (SELECT c_id FROM test WHERE test_id=123 AND op=1)
AND b.c_id IN (SELECT c_id FROM test WHERE test_id=123 AND op=2)