为每个用户插入月份

时间:2019-05-09 14:54:00

标签: sql-server asp.net-mvc stored-procedures

您好,这是我的SP,用于显示旅行顾问的用户行。现在,我想将每个用户的月份放在“月份”列中。

例如:

jan | user1| valueX
Jan ! user2| valueX
Jan | user3| valueX
Fev | user1| valueX
Fev | user2| valueX
Fev | user3| valueX

ALTER PROCEDURE [dbo].[SP_UserTC_BY__ProfID_FuncID]
    @P_ProfileName nvarchar(50)

    --SET @P_FunctionID = 1
    AS
        IF @P_ProfileName is null
            RAISERROR('Null values not allowed for @P_ProfileName', 16,1)

    BEGIN

    SELECT users.UserID, salesobj.Month, users.Name, prof.ProfileName, funct.Name as FunctionName, salesobj.SalesObjectiveMonth, salesobj.GrossMargin, salesobj.ReductionWorkingTime,salesobj.ConversionRate, salesobj.ReductionOnPace
    FROM TBL_User as users join  REL_ProfileUser as relprofileuser
    on users.UserID = relprofileuser.UserID
    join TBL_Profile as prof on prof.ProfileID = relprofileuser.ProfileID
    join TBL_UserFunction as funct on funct.FunctionID = relprofileuser.FunctionID
    FULL OUTER JOIN TBL_SalesObjective as salesobj on salesobj.UserID = users.UserID

    WHERE prof.ProfileName = @P_ProfileName and users.IsActive = 1
    END

我该怎么办?

1 个答案:

答案 0 :(得分:0)

加入表格之前,您需要对所有月份和所有用户进行笛卡尔乘积运算。

ALTER PROCEDURE [dbo].[SP_UserTC_BY__ProfID_FuncID]
    @P_ProfileName nvarchar(50)
--SET @P_FunctionID = 1
AS
    IF @P_ProfileName is null
        RAISERROR('Null values not allowed for @P_ProfileName', 16,1);

BEGIN
    WITH cteUsers AS(
        SELECT *
        FROM TBL_User as users
        CROSS JOIN (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12))x(Month) /*this can be changed to names if needed*/
    )
    SELECT users.UserID, 
            salesobj.Month, 
            users.Name, 
            prof.ProfileName, 
            funct.Name as FunctionName, 
            salesobj.SalesObjectiveMonth, 
            salesobj.GrossMargin, 
            salesobj.ReductionWorkingTime,
            salesobj.ConversionRate, 
            salesobj.ReductionOnPace
    FROM cteUsers                as users 
    join  REL_ProfileUser        as relprofileuser on users.UserID     = relprofileuser.UserID
    join TBL_Profile             as prof           on prof.ProfileID   = relprofileuser.ProfileID
    join TBL_UserFunction        as funct          on funct.FunctionID = relprofileuser.FunctionID
    LEFT JOIN TBL_SalesObjective as salesobj       on salesobj.UserID  = users.UserID
                                                  and salesobj.Month   = users.Month
    WHERE prof.ProfileName = @P_ProfileName 
    and users.IsActive = 1;
END;