具有动态列和JOINS 5+表的PIVOT

时间:2019-04-04 12:42:28

标签: sql sql-server pivot outer-join dynamic-columns

这是我之前发布的问题的扩展,可以在此处找到:Previous Question

现在我还有2个表,这些表也连接到ProfileFan,以跟踪粉丝的活动(ProfileFan)。

Table Fan
-----------------------
| FanId | Name | Info |
-----------------------
| 17111 | Fan1 | Info1|
-----------------------  
| 17112 | Fan2 | Info2|
-----------------------

    Table ProfileFan m:1 Fan FanId(FK)
    -----------------------------------
    | Id | LinkedInProfileId | FanId |
    -----------------------------------
    | 1111    | 1          | 17111   |
    ---------------------------------
    | 1112    | 2          | 17111   |
    ----------------------------------
    | 1113    | 1          | 17112   |
    ----------------------------------
    | 1114    | 2          | 17112   |
    ----------------------------------

    Table LinkedInProfile
    --------------------------
    | Id   | Name    | Client |
    --------------------------
    | 1    | Linked1 | Client1|
    --------------------------
    | 2    | Linked2 | Client1|
    --------------------------

    Table FanActivity m:1 ProfileFan via ProfileFanId (FK)
    ------------------------------------------------
    | Id   | Created    | ProfileFanId | ActivityId |
    -------------------------------------------------
    | 1    | 2019-01-05 |    17111     |     1      |
    -------------------------------------------------
    | 2    | 2019-01-05 |    17111     |     2      |
    -------------------------------------------------
    | 3    | 2019-01-05 |    17112     |     3     |
    -------------------------------------------------
    | 4    | 2019-01-05 |    17112     |     4      |
    -------------------------------------------------

    Table Activity Id(PK) 
    --------------------
    | Id   | Name        | 
    ---------------------
    | 1    | ConAccepted |
    ---------------------
    | 2    | Message     |
    ---------------------
    | 3    | LikesContent |  
    ----------------------
    | 4    | JoinsGroup  |        
    ----------------------

    Table DeliveryActions m:1 ProfileFan via ProfileFanId (FK)
    ------------------------------------------------------
    | Id   | LoggedAt   | ProfileFanId | DeliveryActionId |
    -------------------------------------------------------
    | 1    | 2019-01-05 |    17111     |     1            |
    ------------------------------------------------------
    | 2    | 2019-01-05 |    17111     |     2            |
    ------------------------------------------------------
    | 3    | 2019-01-05 |    17112     |     3            |
    ------------------------------------------------------
    | 4    | 2019-01-05 |    17112     |     4            |
    ------------------------------------------------------

    Table DeliveryAction Id(PK) 
    ------------------------
    | Id   | Name           | 
    ------------------------
    | 1    | M1             |
    ------------------------
    | 2    | M2             |
    ------------------------
    | 3    | M3             |  
    ------------------------
    | 4    | M4             |        
    ------------------------

查询的输出应如下所示。

    -------------------------------------------------------------------------------------------------------------------------------------------------------
    | Name | Info  | LinkedInProfile1| LinkedInProfile2 | Client |ConAccepted | Message | LikesContent | JoinsGroup |     M1     |    M2     |      M3     |     M4     |
    ---------------------------------------------------------------------------------------------------------------------------------------------------
    | Name1 | Info1|  Linked1(1111)  | Linked2(1112)   | Client1 | 2019-01-05 | 2019-01-06 | 2019-01-07 | 2019-01-08 | 2019-01-09 | 2019-01-05 |2019-01-06 | 2019-01-07 |
    ---------------------------------------------------------------------------------------------------------------------------------------------------
    | Name2 | Info2|  Linked1(1113)  | Linked2(1114)    | Client1 |2019-01-05 | 2019-01-06 | 2019-01-07 | 2019-01-08 | 2019-01-09 | 2019-01-05 |2019-01-05 | 2019-01-0 |
    ---------------------------------------------------------------------------------------------------------------------------------------------------

我需要在查询中为单个风扇插入一行数据,而不是在每行允许插入的风扇中插入多个数据。 到目前为止,根据stackoverflow用户的建议,我已经找到了使用PIVOT和动态查询仅针对LinkedInProfile进行解决方案。

我还在https://rextester.com/live/NYYK67222

上创建了一个模拟

我需要使用FanActivities和DeliveryActions表进行适当的联接,到目前为止,在联接之上,每个FAN将数据放在一行中!

因此1个粉丝低于2个LinkedInProfiles->这将创建2个ProfileFansId。所有profileFans都有很多FanActivities和很多DeliveryAction。

我知道我需要在此处使用带有动态列的PIVOT。但这对我来说是新的。

2 个答案:

答案 0 :(得分:2)

由于您期望的结果与rexter上的示例数据不同,因此我只修改了FanActivities&DeliveryActions表中的少量数据。

CREATE TABLE #Fan (FanId INT, Name VARCHAR(100), Info VARCHAR(100));

INSERT INTO #Fan
VALUES (17111, 'Fan1', 'Info1'), (17112, 'Fan2', 'Info2');

CREATE TABLE #LinkedInProfile (Id INT, Name VARCHAR(100), Client VARCHAR(100));

INSERT INTO #LinkedInProfile
VALUES (1, 'Linked1', 'Client1'), (2, 'Linked2', 'Client1');

CREATE TABLE #ProfileFan (Id INT, ProfileId INT, FanId INT);

INSERT INTO #ProfileFan
VALUES (1111, 1, 17111), (1112, 2, 17111), (1113, 1, 17112), (1114, 2, 17112);

CREATE TABLE #Activities (Id INT, Name VARCHAR(100));

INSERT INTO #Activities
VALUES (1, 'ConAccepted'), (2, 'Message'), (3, 'LikesContent'), (4, 'JoinsGroup');

CREATE TABLE #FanActivities (Id INT, Created VARCHAR(100), ProfileFanId INT
                           , ActivityId INT);

INSERT INTO #FanActivities
VALUES 
  (1, '2019-01-05', 1111, 1), (1, '2019-01-05', 1111, 2)
, (1, '2019-01-05', 1112, 3), (1, '2019-01-05', 1111, 4)
, (1, '2019-01-05', 1113, 1), (1, '2019-01-05', 1113, 2)
, (1, '2019-01-05', 1114, 3), (1, '2019-01-05', 1113, 4);

CREATE TABLE #DeliveryAction (Id INT, Name VARCHAR(100));

INSERT INTO #DeliveryAction
VALUES (1, 'M1'), (2, 'M2'), (3, 'M3'), (4, 'M4');

CREATE TABLE #DeliveryActions (Id INT, Created VARCHAR(100), ProfileFanId INT
                            , ActivityId INT);

INSERT INTO #DeliveryActions
VALUES 
  (1, '2019-01-05', 1111, 1), (1, '2019-01-05', 1111, 2)
, (1, '2019-01-05', 1112, 3), (1, '2019-01-05', 1111, 4)
, (1, '2019-01-05', 1113, 1), (1, '2019-01-05', 1113, 2)
, (1, '2019-01-05', 1114, 3), (1, '2019-01-05', 1113, 4);

您的查询将是

;WITH CTE AS(
SELECT F.FanId,F.Name AS FANNAME,F.Info 
,CONCAT(lip.Name,'(',pf.Id,')') AS LINKEDPROFILE
,CONCAT('#LinkedInProfile',pf.ProfileId) as LipId 
, LIP.Client
,FACT.Name AS FANACTIVITY, FA.Created FANACTIVITYDATE
,DA.Name AS DELVACTIVITY, DAS.Created DELVACTIVITYDATE
FROM #Fan F
LEFT JOIN #ProfileFan pf ON f.FanId = pf.FanId
LEFT JOIN #LinkedInProfile lip ON pf.ProfileId = lip.Id
LEFT JOIN #FanActivities FA ON PF.Id = FA.ProfileFanId
LEFT JOIN #ActivitieS FACT ON FACT.Id = FA.ActivityId
LEFT JOIN #DeliveryActions DAS ON PF.Id = DAS.ProfileFanId
LEFT JOIN #DeliveryAction DA ON DAS.ActivityId = DA.ID
)
SELECT FANNAME, Info, Client
,[#LinkedInProfile1],[#LinkedInProfile2]
,[ConAccepted],[Message],[LikesContent],[JoinsGroup]
,[M1],[M2],[M3],[M4] FROM (
SELECT  FANNAME, Info, Client,KEYS,VALUE
FROM CTE
CROSS APPLY (
    VALUES (LipId, LINKEDPROFILE)
    , (FANACTIVITY,FANACTIVITYDATE)
    ,(DELVACTIVITY,DELVACTIVITYDATE)
    )AS TAB(KEYS,VALUE)
)AS A
PIVOT
(
    MAX(VALUE) FOR KEYS IN ([#LinkedInProfile1],[#LinkedInProfile2]
    ,[ConAccepted],[Message],[LikesContent],[JoinsGroup]
    ,[M1],[M2],[M3],[M4])
)PV

我得到的结果

+---------+-------+---------+-------------------+-------------------+-------------+------------+--------------+------------+------------+------------+------------+------------+
| FANNAME | Info  | Client  | #LinkedInProfile1 | #LinkedInProfile2 | ConAccepted |  Message   | LikesContent | JoinsGroup |     M1     |     M2     |     M3     |     M4     |
+---------+-------+---------+-------------------+-------------------+-------------+------------+--------------+------------+------------+------------+------------+------------+
| Fan1    | Info1 | Client1 | Linked1(1111)     | Linked2(1112)     | 2019-01-05  | 2019-01-05 | 2019-01-05   | 2019-01-05 | 2019-01-05 | 2019-01-05 | 2019-01-05 | 2019-01-05 |
| Fan2    | Info2 | Client1 | Linked1(1113)     | Linked2(1114)     | 2019-01-05  | 2019-01-05 | 2019-01-05   | 2019-01-05 | 2019-01-05 | 2019-01-05 | 2019-01-05 | 2019-01-05 |
+---------+-------+---------+-------------------+-------------------+-------------+------------+--------------+------------+------------+------------+------------+------------+

答案 1 :(得分:1)

该帖子中的示例代码与您的rextester示例之间存在一些差异(例如,您帖子中的DeliveryActions.ProfileFanId似乎引用了Fan.FanId,但在rextester示例中,它引用了ProfileFan.Id)。我的答案是根据您的前三个月样本得出的。

我个人的喜好是在不需要的情况下不要执行多个枢轴操作,而是使用交叉表查询...对于我来说,查看和理解要比拥有多个枢轴操作要容易得多。< / p>

您可以在here月份看到它。

import React, { Component } from 'react';
import { Actions } from 'react-native-router-flux';
import NetInfo from "@react-native-community/netinfo";
import { StyleSheet, Text, View, Button } from 'react-native';
import AsyncStorage from "@react-native-community/async-storage";


export default class NetworkStatusProvider extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        status: "Unknown"
      }
    }
    componentDidMount() {
        NetInfo.isConnected.addEventListener(
            'connectionChange',
            isConnected => {

            this.setState({ status: isConnected ? "Connected" : "Not connected" });

        }
        );
    }

    render() {
        return <Text>{this.state.status}</Text>
    }
}