MSSQL:没有聚合函数的Transpose-Pivot表

时间:2019-05-06 08:58:32

标签: sql sql-server pivot aggregate transpose

  

我需要有关MS SQL Transpose的帮助。我尝试了许多枢轴代码,但它们对我的数据没有帮助。   这是我的数据。   enter image description here

我想对它进行转置(枢轴)而没有聚合。数据应该是这样的,

enter image description here

我尝试了以下代码;

SELECT * 
FROM (
        SELECT
        dm
        ,max(hucre) as mxhucre
        FROM #dene
        group by dm 
        ) as pTablom
PIVOT
(
        max(mxhucre)
        FOR dm IN (
        [1000_TEKİRDAĞ TM]
        ,[10000_TEKIRDAG OB1]
        ,[10100_YAĞCI DM]
))AS Pvt

但是得到了

enter image description here

这不是我想要的数据。大部分价值已经消失

如果我不使用聚集(最大-最小等),则该代码将无效。

请帮助

3 个答案:

答案 0 :(得分:6)

使用条件聚合

SELECT 
    max(case when dm='1000_TEKİRDAĞ TM' then hucre end) as '1000_TEKİRDAĞ TM'
    max(case when dm='10000_TEKIRDAG OB1'then hucre end) as '10000_TEKIRDAG OB1',
    max(case when dm='10100_YAĞCI DM  H04_T10' then hucre end) as '10100_YAĞCI DM  H04_T10'
FROM #dene
group by dm

答案 1 :(得分:0)

首先,您可以像这样使用聚合:

with t as (
      select t.*,
             row_number() over (partition by dm order by (select null)) as seqnum
      from <your table> t
     )
select max(case when dm = '1000_TEKİRDAĞ TM' then hucre end) as [1000_TEKİRDAĞ TM],
       max(case when dm = '10000_TEKIRDAG OB1' then hucre end) as [10000_TEKIRDAG OB1]
       max(case when dm = '10100_YAĞCI DM  H01_T10' then hucre end) as [10100_YAĞCI DM  H01_T10]
from t
group by seqnum;

您可以通过使用联接来做到这一点而无需聚合:

with t as (
      select t.*,
             row_number() over (partition by dm order by (select null)) as seqnum
      from <your table> t
     )
select t1.hucre, t2.hucre, t3.hucre
from t t1 left join
     t t2
     on t2.seqnum = t1.seqnum
        t2.dm = '10000_TEKIRDAG OB1' left join
     t t3
     on t3.seqnum = t1.seqnum
        t3.dm = '10100_YAĞCI DM  H01_T10' left join
where t1.dm = '1000_TEKİRDAĞ TM';

答案 2 :(得分:0)

但是我有652 dm。因此很难一一写完所有