在SQL Server中获得季度的服务

时间:2018-09-04 19:44:08

标签: sql sql-server-2012

我有这个查询

CREATE TABLE #TEMP
(
    PRODUCTCLASS NVARCHAR(50),
    YEAR INT,
    QUARTER INT,
    CUSTOMERCOUNT BIGINT
)

INSERT INTO #TEMP (PRODUCTCLASS, YEAR, QUARTER, CUSTOMERCOUNT)
    SELECT 
        PROD.PRODUCTCLASS,
        DATEPART(YEAR, P.ACTUALDT),
        DATEPART(QUARTER, P.ACTUALDT),
        ISNULL(COUNT(P.CUSTOMERCODE), 0)
    FROM 
        POSTINGS AS P,  PRODUCTPOSTINGS R 
    WHERE 
        PRODID = P.PRODID 
    GROUP BY  
        PRODUCTCLASS, DATEPART(YEAR, P.ACTUALDT), DATEPART(QUARTER, P.ACTUALDT) 

SELECT * FROM #TEMP 

以上查询仅得出日期的四分之一。查询返回以下结果:

     PRODUCTCLASS    YEAR   QUARTER  CUSTOMERCOUNT
     ---------------------------------------------
        CRAFT        2018     3         20
        DANCE        2017     2         18
        CRAFT        2018     1         12
        DANCE        2018     4         10

结果集应包含该特定年份的所有季度,而不考虑日期;如果该季度没有业务,则显示为NULL。

我需要这样的结果集:

     PRODUCTCLASS        YEAR   QUARTER   CUSTOMERCOUNT
     ---------------------------------------------------
            CRAFT        2018     1         12
            CRAFT        2018     2         null
            CRAFT        2018     3         20
            CRAFT        2018     4         null
            DANCE        2017     1         NULL
            DANCE        2017     2         18
            DANCE        2017     3         NULL
            DANCE        2017     4         NULL
            DANCE        2018     1         NULL
            DANCE        2018     2         NULL
            DANCE        2018     3         NULL
            DANCE        2018     4         10

我尝试使用日期函数,但无法获得所需的结果。

寻找了与EOMONTH类似的功能,但无法获得所需的结果。

请提供帮助。

1 个答案:

答案 0 :(得分:0)

我会尝试使用CTE进行此操作。

WITH 
Qrtr(Q) AS (
  SELECT 1 
  UNION ALL
  SELECT Q + 1 FROM Qrtr
  WHERE Q < 4
),
Yr(Y) AS (
  SELECT 2018 
  UNION ALL
  SELECT Y - 1 FROM Yr
  WHERE Y > 2018 - 5
),
Cls(C) AS (
  SELECT 'CRAFT' 
  UNION 
  SELECT 'DANCE' 
)
SELECT CTE.C , CTE.Y , CTE.Q , DB.[Num] 
FROM ( 
SELECT C , Y , Q FROM Cls AS C, Yr AS Y, Qrtr AS Q ) AS CTE 
LEFT OUTER JOIN 
( SELECT R.PRODUCTCLASS , R.YEAR , R.QUARTER , COUNT(ISNULL(P.CUSTOMERCODE,0) AS [Num] FROM PRODUCTPOSTINGS AS R
  INNER JOIN POSTINGS AS P ON P.PRODID = R.PRODID ) AS DB 
ON DB.YEAR = CTE.Y AND DB.QUARTER = CTE.Q AND DB.PRODUCTCLASS = CTE.C
GROUP BY CTE.C, CTE.Y, CTE.Q 
ORDER BY C, Y DESC, Q ASC;