如何合并具有相同名称的SQL Pivot的行

时间:2019-05-30 15:33:32

标签: sql-server group-by pivot distinct

我正在尝试对SQL Server中的某些数据进行非规范化,并且能够成功地旋转引用表,但希望能够像行一样进行合并。

枢轴执行如下

select distinct 
'name' = sFname + ' ' + sLname,
advanced, 
basic, 
standard

from
(select * from dbName..person where deleteFlag <> 'Y') as tableTemp
pivot (
  count(serviceType)
  for serviceType IN (advanced, basic, standard)
) as tablePivot

返回

name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   0   |    0
abby a    |     0    |   1   |    0
charlie c |     0    |   1   |    0
charlie c |     0    |   0   |    1

但是我想以这种形式退回

name      | advanced | basic | standard
----------+----------+-------+---------
abby a    |     1    |   1   |    0
charlie c |     0    |   1   |    1

原始数据的结构类似

sFname   | sLname   | serviceType |
---------+----------+-------------+
abby     |     a    |   advanced  |
abby     |     a    |   basic     |
charlie  |     c    |   basic     |
charlie  |     c    |   standard  |

如何运行group byselect distinct之类的操作以在SQL Server中返回合并的数据透视表?

1 个答案:

答案 0 :(得分:1)

您需要在PIVOT之前限制子查询中的列。

SELECT [name], 
       [advanced], 
       [basic], 
       [standard]
FROM   (
           SELECT 'name' = sFname + ' ' + sLname, 
                  serviceType
           FROM   person
           WHERE  deleteFlag <> 'Y'
       ) AS tableTemp 
PIVOT(COUNT(serviceType) FOR serviceType IN(advanced, basic, standard)) AS tablePivot;