如何在有条件的循环中选择列

时间:2019-06-26 15:23:47

标签: sql sql-server tsql pivot

我有这个查询。 DDIFF只是表中两个Date列的区别:

SELECT 
    DDIFF,
    SUM(CASE WHEN Franchise = 'Franchise' THEN 1 ELSE 0 END) AS [Franchise Count],
    SUM(CASE WHEN Franchise = 'Own' THEN 1 ELSE 0 END) AS [Own Count]
FROM
    dbo.joined
GROUP BY
    DDIFF, Franchise
ORDER BY
    DDIFF

这是输出的一部分:

DDIFF   Franchise Count Own Count
----------------------------------
NULL    0               1
-31     0               3
-28     0               13
-20     2               0
-16     1               0
-13     0               2
...

我正在获取专营店或“自有”商店的销售数据。

但是我想将这些计数划分为几个月,所以我需要进行某种循环才能在一年中的每个月获得这两个列(即12x2列)

要拥有这样的东西:

DDIFF   [2019.01 Franchise] [2019.01 Own] [2019.02 Franchise] [2019.02 Own] ...
-------------------------------------------------------------------------
NULL    0                   1             0                   1
-31     0                   0             2                   1
-28     0                   10            0                   3
-20     1                   0             1                   0
-16     1                   0             0                   0
-13     0                   1             0                   1
...

我想我需要创建某种循环并在AND dateColumn = year.month处添加一个CASE WHEN条件,以建立该月的实际列,甚至需要一个涵盖多年的嵌入式循环

是否有一种语法可以让我创建像这样的列?

1 个答案:

答案 0 :(得分:2)

我认为您想要这样的东西:

SELECT 
    DDIFF,
    SUM(CASE WHEN Franchise = 'Franchise' and month(datefiled) = 1 THEN 1 ELSE 0 END) AS [2019.1 Franchise Count],
    SUM(CASE WHEN Franchise = 'Own' and month(datefiled) = 1 THEN 1 ELSE 0 END) AS [2019.1 Own Count],

    SUM(CASE WHEN Franchise = 'Franchise' and month(datefiled) = 2 THEN 1 ELSE 0 END) AS [2019.2 Franchise Count],
    SUM(CASE WHEN Franchise = 'Own' and month(datefiled) = 2 THEN 1 ELSE 0 END) AS [2019.2 Own Count],

    SUM(CASE WHEN Franchise = 'Franchise' and month(datefiled) = 3 THEN 1 ELSE 0 END) AS [2019.3 Franchise Count],
    SUM(CASE WHEN Franchise = 'Own' and month(datefiled) = 3 THEN 1 ELSE 0 END) AS [2019.3 Own Count],

-- etc

FROM  dbo.joined
GROUP BY DDIFF
ORDER BY DDIFF