如何在查询中获取Row in Column

时间:2018-04-26 10:43:51

标签: sql sql-server

我在我的sql数据库中有这个视图:

enter image description here

我的视图中有IdEsame = 39

的值
    ID  IdEsame IdParametro Ordinamento Colonna
    72  39      163         1           1
    73  39      164         1           2
    74  39      165         1           3
    75  39      166         2           1
    76  39      167         2           2
    77  39      168         2           3
    78  39      169         3           1
    79  39      170         3           2
    80  39      171         3           3

现在我想构建一个查询,用Ordinamento Column设置列中的行。

这个返回此结果集的查询

ID  IdEsame IdParametro IdParametro2    IdParametro3
72  39      163         164             165
73  39      166         167             168
74  39      169         170             171

2 个答案:

答案 0 :(得分:1)

尝试这个:解决方案将是动态PIVOT,如下所示,但ID将返回每组minimum的{​​{1}},我希望您也想要相同的

Ordinamento

<强>输出:

CREATE TABLE #temp(ID INT,  IdEsame INT, IdParametro INT, Ordinamento INT, Colonna INT)
INSERT INTO #temp VALUES
(72,39,163,1,1),
(73,39,164,1,2),
(74,39,165,1,3),
(75,39,166,2,1),
(76,39,167,2,2),
(77,39,168,2,3),
(78,39,169,3,1),
(79,39,170,3,2),
(80,39,171,3,3)

DECLARE @col VARCHAR(1000)
DECLARE @sql VARCHAR(2000)

SELECT @col = 
    COALESCE(@col + ', ','') + QUOTENAME('IdParametro' + CAST(Colonna AS VARCHAR))
FROM #temp
GROUP BY Colonna

SET @sql = '
SELECT t.ID, IdEsame, ' + @col + '
FROM (SELECT 
        IdEsame, 
        IdParametro,
        CONCAT(''IdParametro'',Colonna) AS Colonna,
        Ordinamento
    FROM #temp)p
PIVOT(MAX (IdParametro) FOR Colonna IN ( ' + @col + ' )
) AS pvt
OUTER APPLY( SELECT MIN(id) AS ID 
            FROM #temp t WHERE t.Ordinamento = pvt.Ordinamento) t'

EXEC (@sql)

答案 1 :(得分:0)

一种方法使用条件聚合:

select min(id), idesame,
       max(case when colonna = 1 then IdParametro end) as IdParametro1,
       max(case when colonna = 2 then IdParametro end) as IdParametro2,
       max(case when colonna = 3 then IdParametro end) as IdParametro3
from t
group by Ordinamento, idesame;

我不明白第一列的分配方式。数字似乎相当随意,但我推测你想要每行的最小id。