我正在使用MS SQL服务器。
我在查询中使用了 pivot 。我已经完成的工作如下:
--/*==========================================================
--
--
--
--===========================================================*/
--CREATE VIEW View_BASequenceExportDtl
--AS
--ALTER PROCEDURE Proc_BASequenceExportDtl
--AS
DECLARE @cols NVARCHAR(MAX)
DECLARE @stmt NVARCHAR(MAX)
SET @cols = ISNULL(@cols + ', ', '') (
SELECT Table3.vAnalyteName
FROM Table3,BaSequenceScheduleHdr,BAAnalyteSampleHdr
WHERE Table3.nTable2No = BaSequenceScheduleHdr.nTable2No
AND Table3.cStatusIndi <> 'D'
)
SET @stmt = 'SELECT
Table1.nBaSequenceScheduleHdrNo,
Table1.vSampleId,
Table1.vSampleName,
Table1.iSeqNo,
Table1.vSampleType,
Table2.vInjectionVolume,
Table3.vAnalyteName,
Table4.nConcentration,
Table1.cStatusIndi
FROM Table1
INNER JOIN BaSequenceScheduleHdr
ON(BaSequenceScheduleHdr.nBaSequenceScheduleHdrNo = Table1.nBaSequenceScheduleHdrNo
AND BaSequenceScheduleHdr.cStatusIndi <> ''D'')
INNER JOIN Table2
ON(Table2.nTable2No = BaSequenceScheduleHdr.nTable2No
AND Table2.cStatusIndi <> ''D'')
INNER JOIN Table3
ON(Table3.nTable2No = BaSequenceScheduleHdr.nTable2No
AND Table3.cStatusIndi <> ''D'')
LEFT JOIN BAAnalyteSampleHdr
ON(BAAnalyteSampleHdr.nTable2No = BaSequenceScheduleHdr.nTable2No
AND BAAnalyteSampleHdr.nTable3No = Table3.nTable3No
AND BAAnalyteSampleHdr.cStatusIndi <> ''D'')
LEFT JOIN Table4
ON(Table4.nBAAnalyteSampleHdrNo = BAAnalyteSampleHdr.nBAAnalyteSampleHdrNo
AND Table4.vSampleID = Table1.vSampleId
AND Table4.cStatusIndi <> ''D'')
PIVOT (
SUM(Table4.nConcentration) FOR Table3.vAnalyteName IN ( ' + @cols + ' )
) AS PVT'
exec(@stmt)
此处concentration
取决于Analyte
。所以我想要的是,根据动态Analyte
名称,其concentration
应位于该列之下。
在此处,首先@cols
将包含将传递给 analyte
的所有PIVOT
个名称。最终的 exec(@stmt)
应该将所有数据作为 View
但我收到错误: (10 row(s) affected) Msg 102, Level 15, State 1, Line 37 Incorrect syntax near ')'.
而且,我第一次使用 pivot 。所以,如果有任何错误,请告诉我。
答案 0 :(得分:0)
这部分没有意义
SET @cols = ISNULL(@cols + ', ', '') (
SELECT Table3.vAnalyteName
FROM Table3,BaSequenceScheduleHdr,BAAnalyteSampleHdr
WHERE Table3.nTable2No = BaSequenceScheduleHdr.nTable2No
AND Table3.cStatusIndi <> 'D'
)
答案 1 :(得分:0)
构建以逗号分隔的列列表的方式需要更改。将其更改为:
DECLARE @cols NVARCHAR(MAX) = N''
SELECT @cols = @cols + N', ' + Table3.vAnalyteName
FROM Table3,BaSequenceScheduleHdr,BAAnalyteSampleHdr
WHERE Table3.nTable2No = BaSequenceScheduleHdr.nTable2No
AND Table3.cStatusIndi <> 'D'
set @cols = stuff(@cols, 1, 2, N'')