透视SQL结果

时间:2019-01-13 15:23:51

标签: sql sql-server

我有此查询,并且希望以某种方式透视结果,以便在一定程度上获得Assigned To中的=IIf ( DLookUp("[E-mail Address]","Contacts","[ID]=" & Nz([Opened By],0))= DLookUp("[E-mail Address]","Contacts","[ID]=" & Nz([Assigned To],0)), "email@email.com", DLookUp("[E-mail Address]","Contacts","[ID]=" & Nz([Opened By],0)) & ";email@email.com" ) AirlineCode中的y-axis年。该查询现在对我来说是正确的事情,但是将所有内容复制到Excel并由我自己进行排序有点费劲。

Month

1 个答案:

答案 0 :(得分:0)

您是否正在寻找类似的东西?

WITH MonthsStartDates AS
(
    SELECT
        MonthStartDate = CONVERT(DATE, '2018-01-01')

    UNION ALL

    SELECT
        MonthStartDate = DATEADD(MONTH, 1, M.MonthStartDate)
    FROM
        MonthsStartDates AS M
    WHERE
        M.MonthStartDate <= '2020-01-01'
), Wth1 as 
(

    SELECT 
        AirlineCode,
        Year = DATEPART(YEAR, M.MonthStartDate),
        Month = DATEPART(MONTH, M.MonthStartDate),
        AppUser = COUNT(DISTINCT AppUser.Id)
    FROM 
        [followme.aero.live].[dbo].[AppUser]
        INNER JOIN [followme.aero.live].[dbo].[UserInAppPurchase] ON AppUser.Id = UserInAppPurchase.UserId
        INNER JOIN MonthsStartDates AS M ON
            PurchaseDate < M.MonthStartDate AND
            ValidTo > M.MonthStartDate
    GROUP BY 
        AirlineCode,
        DATEPART(YEAR, M.MonthStartDate),
        DATEPART(MONTH, M.MonthStartDate)
)
SELECT 
   AirlineCode,
   Year, 
   AppUser
   [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]
FROM (
  SELECT * FROM WTh1
  PIVOT 
  ( 
    SUM(AppUser)
    For Month In ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
  ) as PivotTable;