简体   繁体   English

如何创建一个新表,其中列基于其他表上的键?

[英]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)

Here it is running on SEDE. 这里是上SEDE运行。

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.

相关问题 如何创建具有两个主键的表,其中一个是一个表中的外键,另一个是另一个表中的外键? - how to create a table with two primary keys where one is foreign key in one table and the other on another table? 在SQL表中创建映射到其他表的主键的列 - Create columns in SQL table that map to primary keys of other table MySQL-基于外键与其他表的自定义附加列 - MySQL - custom, additional columns based on foreign keys with other table 如何删除多列IN \\ NOT IN其他表中的位置? - how to Delete where multiple columns IN\NOT IN other table? 如何创建表,其中第一个表中的列是另一个表中的字段? - How to create table where columns in first table are fields in another table? 如何基于其他列中的值更新表 - How to update table based on the values in other columns 根据现有表的条件创建新列 - creating new columns based off where conditions of existing table 创建聚合 SQL 报告,其中列基于表列表 - Create aggregated SQL report where the columns are based on a table list 创建具有基于其他表列值生成的布尔列的表? - create a table with a Boolean column generated based on other tables columns values? 如何根据其他列的排名在表中设置新列? - How can I set a new column in a table based on the rank of other columns?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM