分组/透视表

时间:2019-07-12 20:28:32

标签: sql sql-server

我试图在不使用聚合函数的情况下透视表

我尝试了2个枢轴的获取最大和最小名称,但是它不起作用

Declare @test table()
   Name varchar(30) not null,
   Grade varchar(10) not null,
   Subject varchar(10) not null
)

insert into @test values('Ami', 'HD', 'Java')
insert into @test values('Ami', 'D', 'C++')
insert into @test values('Bec', 'D', 'Java')
insert into @test values('Bec', 'P', 'C++')
insert into @test values('Bec', 'Pa', 'C++')

select * from @test

select Name, Max(case Subject when 'C++'  then Grade end) 'C++',
             Max(case Subject when 'Java' then Grade end) 'Java'
from @test
group by Name



SELECT * FROM
(
select Name, grade, subject from @test
)x
PIVOT
(
    MIN(grade)
    for subject IN ([JAVA],[C++])
)p

这是我的输出 output

我的例外输出: excepted output

2 个答案:

答案 0 :(得分:1)

您可以使用CTE添加一个ROW_NUMBER值,然后将其添加到您的GROUP BY中。我还将逻辑更改为“交叉表”,因为它们比内置PIVOT运算符更加灵活:

WITH CTE AS(
    SELECT [Name],
           Grade,
           Subject,
           ROW_NUMBER() OVER (PARTITION BY [Name], Subject ORDER BY Grade) AS RN
    FROM @test t)
SELECT [Name],
       MAX(CASE Subject WHEN 'C++' THEN Grade END) AS [C++],
       MAX(CASE Subject WHEN 'Java' THEN Grade END) AS [Java]
FROM CTE
GROUP BY [Name],
         RN;

答案 1 :(得分:1)

如果您要使用PIVOT(条件汇总为+1)

示例

Select * 
 From  (
        Select [RN]   = row_number() over (partition by [name],[Subject] order by Grade Desc)
              ,[Name]
              ,[Grade]
              ,[Subject]
        From @test
       ) src
 Pivot ( max(grade) for subject IN ([C++],[JAVA]) )p

返回

RN  Name    C++ JAVA
1   Ami     D   HD
1   Bec     Pa  D
2   Bec     P   NULL