PIVOT SQL Server中的两个表没有聚合

时间:2017-09-13 20:52:10

标签: sql sql-server

我在将行转换为列时遇到问题。

我的结构是这样的:

SELECT 
    [ID_KPI]
   ,[KPI_VALUE]
FROM [dbo].[FACT_KPI]

SELECT 
    ID_KPI
   ,KPI_LABEL
FROM [dbo].[DIM_KPI]

INPUT

我想要实现的输出

SELECT 
    [nb_departure]
   ,[nb_arrival]
   ,[headcount]
FROM [dbo].[FACT_HR]

OUTPUT

2 个答案:

答案 0 :(得分:1)

您可以使用以下角色:

Select nb_departure, nb_arrival, headcount from (
    Select d.KPI_LABEL, f.KPI_VALUE
    , RowN = Row_Number() over(order by d.id_kpi)
        from dbo.Fact_KPI f
        join dbo.Dim_KPI d
        on f.ID_KPI = d.ID_KPI
) a
pivot (max(kpi_value) for kpi_label in ([nb_departure],[nb_arrival],[headcount])) p

输出如下:

+--------------+------------+-----------+
| nb_departure | nb_arrival | headcount |
+--------------+------------+-----------+
| 25           | NULL       | NULL      |
| 30           | NULL       | NULL      |
| NULL         | 15         | NULL      |
| NULL         | 7          | NULL      |
| NULL         | NULL       | 12        |
| NULL         | NULL       | 13        |
+--------------+------------+-----------+

答案 1 :(得分:0)

您可以使用CTE或派生表以及一些条件聚合来执行此操作。我不知道你的意思没有聚合,我不确定这是否可能没有聚合:

CTE:

CREATE TABLE FACT_KPI (ID_KPI int, KPI_VALUE int)
CREATE TABLE DIM_KPI (ID_KPI int, KPI_LABEL varchar(25))

INSERT INTO FACT_KPI VALUES (1,25)
                        ,(1,30)
                        ,(2,15)
                        ,(2,7)
                        ,(3,12)
                        ,(3,13)

INSERT INTO DIM_KPI VALUES (1, 'nb_departure')
                       ,(2, 'nb_arrival')
                       ,(3, 'headcount')
SELECT CASE WHEN ID_KPI = 1 THEN KPI_VALUE END AS nb_departure,
   CASE WHEN ID_KPI = 2 THEN KPI_VALUE END AS nb_arrival,
   CASE WHEN ID_KPI = 3 THEN KPI_VALUE END AS headcount
FROM       
(SELECT F_KPI.ID_KPI, KPI_VALUE, KPI_LABEL
FROM FACT_KPI F_KPI
INNER JOIN DIM_KPI ON F_KPI.ID_KPI = DIM_KPI.ID_KPI) FACT_KPI

派生表:

{{1}}

其他注意事项,请在下次使用ASCII表格时阅读Sean Lange评论的内容。