透视功能

时间:2016-07-19 22:53:26

标签: sql-server

我尝试在AdventureWorks2014数据库上创建一个函数,用于将客户分类为每年的A,B和C类

    CREATE FUNCTION udf_CustomersClassification(@year int)
    RETURNS @TABLE TABLE (TOPRANK NVARCHAR(1), ID INT, FULLNAME NVARCHAR(MAX))
    AS
    BEGIN
        INSERT INTO @TABLE
            SELECT  CASE
                        WHEN TOTAL > 100000 THEN 'A'
                        WHEN TOTAL > 50000 THEN 'B'
                        ELSE 'C'
                    END AS RN,
                    CustomerID,
                    FULLNAME
            FROM(
                SELECT  SOH.CustomerID,
                        PP.FirstName + ' ' + PP.LastName AS FULLNAME,
                        SUM(SOD.TOTALORDER) AS TOTAL,
                        YEAR(SOH.OrderDate) AS ORDERYEAR 
                FROM    (
                            SELECT  SalesOrderID, 
                                    SUM(OrderQty*UnitPrice) AS TOTALORDER
                            FROM    Sales.SalesOrderDetail
                            GROUP BY SalesOrderID
                        ) AS SOD
                JOIN    Sales.SalesOrderHeader AS SOH
                ON      SOD.SalesOrderID = SOH.SalesOrderID
                JOIN    Sales.Customer AS C
                ON      SOH.CustomerID = C.CustomerID
                JOIN    Person.Person AS PP
                ON      C.PersonID = PP.BusinessEntityID
                WHERE   YEAR(SOH.OrderDate) = @year
                GROUP BY SOH.CustomerID, 
                        PP.FirstName + ' ' + PP.LastName,
                        YEAR(SOH.OrderDate)) AS A
            ORDER BY TOTAL DESC
        RETURN 
    END
    GO

然后在此函数中计算它们

CREATE FUNCTION udf_CustomersClassOverYears(@startyear int, @endyear int)
RETURNS @TABLE TABLE(CLASS NVARCHAR(1), Cust_No INT, YEAR INT)
AS
BEGIN
    WHILE @startyear <= @endyear
    BEGIN
        INSERT INTO @TABLE
        SELECT  TOPRANK,
                COUNT(ID) AS Cust_Num, 
                @startyear AS YEAR
        FROM    udf_CustomersClassification(@startyear)
        GROUP BY TOPRANK
        ORDER BY TOPRANK, YEAR
    SET @startyear = @startyear + 1
    END
    RETURN
END
GO

然后我尝试了这段代码及其工作

SELECT CLASS, [2012], [2013], [2014] 
FROM udf_CustomersClassOverYears(2012, 2014) AS A
PIVOT(MAX(CUST_NO) 
        FOR YEAR 
            IN ([2012], [2013], [2014])) AS PVT
ORDER BY CLASS

enter image description here

问题是我想在最后一个函数中使用这个旋转而我不能因为列数不是常数,它根据开始和结束年份参数

0 个答案:

没有答案