用于在数据透视表模型中获取数据的SQL查询

时间:2018-02-19 04:51:37

标签: sql linq pivot-table

我正在寻找一个SQL查询来获取数据透视表模型中的sql数据。

SQL表数据

Code    CustomerName    Type        Items         EntryDate
C0001   Thomas          BREAKFAST   Milk          2018-04-25 14:03:12.340
C0001   Thomas          BREAKFAST   Bread         2018-04-20 12:03:12.340
C0001   Thomas          BREAKFAST   Egg           2018-04-25 12:03:12.340 
C0001   Thomas          LUNCH       Rice          2018-04-10 11:03:12.340
C0001   Thomas          LUNCH       Fish Curry    2018-04-12 11:03:12.340
C0001   Thomas          LUNCH       Lessy         2018-04-15 11:03:12.340
C0001   Thomas          DINNER      Bread         2018-04-25 14:03:12.340
C0001   Thomas          DINNER      Jam           2018-04-25 14:03:12.340

使用以下SQl查询

WITH data_CTE( id, Type, Items,RID ,Code, CustomerName)
AS

(

SELECT id, Type, Items,
  ROW_NUMBER() OVER (PARTITION BY (Type)ORDER BY  id) AS RID ,Code, CustomerName
  FROM Table1 

)

SELECT Code, CustomerName, [BREAKFAST], [LUNCH], [DINNER]

FROM

(SELECT  Type, Items,RID ,Code, CustomerName

FROM data_CTE)C

PIVOT

(

max(Items)

FOR Type IN ([BREAKFAST], [LUNCH], [DINNER])

) AS PivotTable;

我输出

Code    CustomerName    BREAKFAST   LUNCH       DINNER
C0001   Thomas          Milk        null        Bread
C0001   Thomas          null        null        Jam
C0001   Thomas          Bread       null        null
C0001   Thomas          Egg         null        null
C0001   Thomas          null        Fish Curry  null
C0001   Thomas          null        Rice        null

如果entrydate不相同,则上面的输出为null。即使还有很多其他字段,我也需要输出如下。

Code    CustomerName    BREAKFAST   LUNCH       DINNER
C0001   Thomas          Milk        Rice        Bread
C0001   Thomas          Bread       Lessy       Jam
C0001   Thomas          Egg         Fish Curry  

请帮忙

先谢谢。

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作。

WITH data_CTE( id, Type, Items,RID ,Code, CustomerName)
AS

(

SELECT id, Type, Items,
  ROW_NUMBER() OVER (PARTITION BY (Type)ORDER BY  id) AS RID ,Code, CustomerName
  FROM Table1 

)

SELECT Code, CustomerName, [BREAKFAST], [LUNCH], [DINNER]

FROM

(SELECT  Type, Items,RID ,Code, CustomerName

FROM data_CTE)C

PIVOT

(

max(Items)

FOR Type IN ([BREAKFAST], [LUNCH], [DINNER])

) AS PivotTable;

以下是Sample Code

答案 1 :(得分:0)

首先,表中有3种类型,所以我打算根据它们的类型给它们一些排名,并且我使用了pivot来获得预期的结果:

SELECT * FROM (
    SELECT DENSE_RANK() OVER  (PARTITION BY TYPE ORDER BY ITEMS DESC ) 
    ID,CODE,CUSTOMERNAME,ITEMS,TYPE FROM YOUR_TABLE
) PIVOT (
    MAX(ITEMS)
    FOR TYPE IN ('BREAKFAST', 'LUNCH','DINNER')
) ORDER BY ID

答案 2 :(得分:0)

请试试这个,希望这对你有所帮助。

SELECT * FROM 
(
SELECT DENSE_RANK() OVER  (PARTITION BY TYPE ORDER BY ITEMS DESC ) 
ID,CODE,CUSTOMERNAME,ITEMS,TYPE FROM YOUR_TABLE
)

PIVOT
(
 MAX(ITEMS)
 FOR TYPE IN ('BREAKFAST', 'LUNCH','DINNER')
) 
ORDER BY ID