如何创建从表中将ROWS放在列中的视图

时间:2018-10-22 14:01:14

标签: sql sql-server tsql

我想从这些表中创建一个复杂的视图。

表1:

CREATE TABLE [dbo].[RRSlotFiltriXDatiAggregatiElaborati](
    [ID] [int] NOT NULL,
    [IdRRSlotFiltri] [int] NOT NULL,
    [idParametro] [int] NULL,
    [idUm] [int] NULL,
    [valore] [decimal](8, 3) NULL,
    [idTipoElaborazione] [int] NULL,
    [idTipoParametro] [int] NULL,
    [idAggregazione] [int] NULL,
 CONSTRAINT [PK_RRSlotXElaborazioniFD] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)

现在在此表中,我具有以下值: enter image description here

现在,如您所见,对于每个参数(id = 11 | 12 | 13),在我的表中有5条记录。记录因idUm,idAggregazione的不同而不同。

现在,我想从该表创建一个视图,该视图包含3行,每个参数(11,12,13)1行,其他5列(Valore列),因此应作为输出:

enter image description here

2 个答案:

答案 0 :(得分:1)

您不能在VIEW中使用动态SQL,但是如果您拥有已知或最大数量的项目,那么使用Row_Number()和PIVOT就很简单了。

示例

Select *
 From  (
        Select idParameter
              ,Item  = concat('valore',row_number() over(partition by idParameter order by id)
              ,value = valore
         From  [dbo].[RRSlotFiltriXDatiAggregatiElaborati]
       ) src
 Pivot (max(value) for Item in ( [valore1],[valore2],[valore3],[valore4],[valore5] ) ) pvt

答案 1 :(得分:0)

您可以使用row_number()并进行条件聚合:

create view v1 as
    select idParameter, 
           max(case when seq = 1 then valore end) as valore1,
           max(case when seq = 2 then valore end) as valore2,
           max(case when seq = 3 then valore end) as valore3,
           max(case when seq = 4 then valore end) as valore4,
           max(case when seq = 5 then valore end) as valore5
    from (select r.*,
                 row_number() over (partition by idParameter order by id) as seq
          from [dbo].[RRSlotFiltriXDatiAggregatiElaborati] r
         ) r
    group by idParameter;