2017-09-13 73 views
0

我有將行轉換爲列的問題。在沒有彙總的情況下在SQL服務器中插入兩個表

我的結構是這樣的:

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

+3

這是一個偉大的地方開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

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') 



;WITH cte_example 
AS 
(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) 

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 cte_example 

派生表:

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 

其他注意事項,請使用ASCII請下次參閱表格並請閱讀Sean Lange評論過的內容。

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  | 
+--------------+------------+-----------+ 
相關問題