一列中的两行SQL Server

时间:2016-11-03 20:34:53

标签: sql sql-server

我有以下查询:

SELECT tbl_SampledParts.Data 
FROM tbl_SampledParts 
INNER JOIN tbl_Inspection ON tbl_SampledParts.InspectionId = tbl_Inspection.InspectionId
WHERE (tbl_Inspection.InspectionDate BETWEEN '2016-10-26' AND '2016-11-03')

Result

这就是我得到的但是我想在我尝试使用此页面中的答案的COALESCEXML查询的一列中显示查询结果,但我不知道如何添加内部联接和条件。此查询显示我想要的结果:

DECLARE @test NVARCHAR(max)  

SELECT @test = COALESCE(@test + ',', '') + Data FROM tbl_SampledParts 

SELECT @test 

但就像我说的那样,我需要我的内心联系以及强制条件,我该怎么做?

更新:日期可能会发生变化,这就是为什么我需要使用与WHERE (tbl_Inspection.InspectionDate between '2016-10-26' and '2016-11-03')完全相同的where条件的原因。

2 个答案:

答案 0 :(得分:1)

您可以将这两个查询组合在一起:

DECLARE @test NVARCHAR(max);

SELECT @test = COALESCE(@test + ',', '') + Data FROM (
SELECT tbl_SampledParts.Data FROM tbl_SampledParts 
INNER JOIN tbl_Inspection ON tbl_SampledParts.InspectionId = tbl_Inspection.InspectionId
WHERE (tbl_Inspection.InspectionDate between '2016-10-26' and '2016-11-03')
) as t;

SELECT @test;

它是

答案 1 :(得分:0)

create table Testdata(Data varchar(max))
insert Testdata select '3.6,1,5.6,7.5,9,2.2,4.6,2.3,6.4,6.5,5,3.7,6,5.4,3,1.5'
insert Testdata select '50,3.72,50,3.72,50,3.72,50,3.72,65.3,72,50,3.72,45,3.72,..'



with tmp(DataItem, Data) as (
select LEFT(Data, CHARINDEX(',',Data+',')-1),
       STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from Testdata
union all
select LEFT(Data, CHARINDEX(',',Data+',')-1),
       STUFF(Data, 1, CHARINDEX(',',Data+','), '')
from tmp
where Data > ''
)
select DataItem
from tmp;