[英]How to create a new table where the columns are based on keys on other table?
In SQL Server 2008, I have the following tables: 在SQL Server 2008中,我具有下表:
CREATE TABLE samples (SampleID int, Time datetime, RawData image)
CREATE TABLE parameters (ParamID, SampleID int, ParamType uniqueidentifier, Value float)
In this scenario my application processes a given sample (from 'samples' table) and extracts several diferent parameters and stores them on the 'paremeters' table. 在这种情况下,我的应用程序处理一个给定的样本(从“样本”表中)并提取几个不同的参数,并将它们存储在“参数表”中。
I would like to create a temporary table where every parameter (defined by a specific ParamType) is a column and every row is defined the values of every parameters extracted from every given sample. 我想创建一个临时表,其中每个参数(由特定的ParamType定义)都是一列,每一行都定义了从每个给定样本中提取的每个参数的值。 The problem is that the number and name of the columns of the result are dependent on the values of the 'parameters' table. 问题在于结果列的数量和名称取决于“参数”表的值。
How can this be done? 如何才能做到这一点?
I am not exactly sure what you are asking, but this should be close to what you want: 我不确定您要问的是什么,但这应该接近您想要的:
DECLARE @columns VARCHAR(MAX)
SELECT @columns =
COALESCE(@columns + ',[' + CAST(p.ParamType as varchar(50)) + ']'
,'[' + CAST(p.ParamType as varchar(50)) + ']')
FROM
(
SELECT DISTINCT ParamType FROM parameters
) as p
DECLARE @query VARCHAR(MAX)
SET @query = '
SELECT * FROM
(
SELECT SampleID, ParamType, Value FROM parameters
) as tbl3
PIVOT
(
AVG(Value) FOR ParamType in (' + @columns + ')
) AS tblResults'
EXECUTE (@query)
I think you need a pivot query 我认为您需要数据透视查询
Try this: 尝试这个:
select * from
(
select SampleID,Value,ParamType from parameters
) AS params
pivot (max(value) for ParamType in ([Type1],[Type2])) as Result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.