通过SQL查询确定趋势;代码说明

时间:2018-10-13 10:50:16

标签: sql sql-server tsql

我是SQL的新手,我正尝试自己学习T-SQL,这是一本初学者的书。我陷入了一个查询,仍然无法解决;为什么起作用,或如何起作用。我希望你能帮助我。

我有桌子:

CREATE TABLE #AnnualSales
(
    YEAR CHAR(4),
    SALE INT
);

INSERT INTO #AnnualSales (YEAR, SALE)
VALUES ('2001', 100), ('2002', 150), ('2003', 120), ('2004', 150),
       ('2005', 250), ('2006', 300), ('2007', 250);

目标是确定按年份排序的销售趋势,其中“ 1”为正,“-1”为负。这本书说我们可以从(1)中做到这一点:

WITH Years AS
(
    SELECT 
        Z.Year, Z.Sale, 
        SIGN(Z.Sale - (SELECT W1.Sale
                       FROM #AnnualSales AS W1
                       WHERE W1.Year = (SELECT MAX(W2.Year)
                                        FROM #AnnualSales AS W2
                                        WHERE W2.Year < Z.Year))) AS Trend
    FROM 
        #AnnualSales AS Z
)
SELECT 
    *, 
    (SELECT COUNT(*)
     FROM Years AS T2
     WHERE T2.Year >= T1.Year 
       AND T2.Trend <> T1.Trend) AS Rows
FROM 
    Years AS T1 

对此(2):

WITH Years AS
(
    SELECT 
        Z.Year, Z.Sale, 
        SIGN(Z.Sale - (SELECT W1.Sale
                       FROM #AnnualSales AS W1
                       WHERE W1.Year = (SELECT MAX(W2.Year)
                                        FROM #AnnualSales AS W2
                                        WHERE W2.Year<Z.Year))) AS Trend
    FROM 
        #AnnualSales AS Z
),
Factor AS
(
    SELECT 
        *, 
        (SELECT COUNT(*)
         FROM Years AS T2
         WHERE T2.Year >= T1.Year AND T2.Trend <> T1.Trend) AS Rows
    FROM 
        Years AS T1
)
SELECT 
    MIN(Year), MAX(Year), Trend
FROM 
    Factor
GROUP BY 
    Rows, Trend
ORDER BY 
    MIN(Year)

我不知道它从(1)到(2)的工作方式。我不明白为什么查询(1)中的结果显示诸如'2'和'3'之类的值,最后一切都按预期运行。

0 个答案:

没有答案