使用union在sql查询中进行透视

时间:2015-12-15 13:36:55

标签: sql sql-server pivot

此查询有什么问题:

 select * from ( select [date],CountType,[Count]  from(

select COUNT(Id) as [Count],'TotalCustomer' as CountType, cast(DATEADD(day,3,[JobCardDate])as date) as [date] FROM [Honda_db].[dbo].[Post Service Feedback] 
where cast(DATEADD(day,3,[JobCardDate]) as date) between '2015-11-26' and  '2015-12-26' group by cast(DATEADD(day,3,[JobCardDate]) as date)
 union  
select COUNT(Id) as [Count],'NotCalled' as CountType, cast(DATEADD(day,3,[JobCardDate]) as date) as [Date] from [Honda_db].[dbo].[Post Service Feedback] 
  where  cast(DATEADD(day,3,[JobCardDate]) as date) between '2015-11-26' and  '2015-12-26' and 
  ([IsCalled] is null or [IsCalled] ='No')  group by cast(DATEADD(day,3,[JobCardDate]) as date)
  ) as s
  PIVOT
(
    SUM([Count])
    FOR CountType IN (TotalCustomer,NotCalled)
) AS pvt

根据枢轴的语法,我认为我走在正确的轨道上。来自this

这是错误:

  

pvt'附近的语法不正确。

1 个答案:

答案 0 :(得分:2)

您有2个错误:

  1. FOR CountType IN (TotalCustomer,NotCalled)这应该是分隔的
  2. 开头的额外select * from (
  3. 以下是更正后的查询:

    SELECT  *
    FROM    ( SELECT    COUNT(Id) AS [Count] ,
                        'TotalCustomer' AS CountType ,
                        CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE) AS [date]
              FROM      [Honda_db].[dbo].[Post Service Feedback]
              WHERE     CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE) BETWEEN '2015-11-26' AND '2015-12-26'
              GROUP BY  CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE)
              UNION
              SELECT    COUNT(Id) AS [Count] ,
                        'NotCalled' AS CountType ,
                        CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE) AS [Date]
              FROM      [Honda_db].[dbo].[Post Service Feedback]
              WHERE     CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE) BETWEEN '2015-11-26' AND '2015-12-26'
                        AND ( [IsCalled] IS NULL
                              OR [IsCalled] = 'No'
                            )
              GROUP BY  CAST(DATEADD(DAY, 3, [JobCardDate]) AS DATE)
            ) AS s PIVOT
    ( SUM([Count]) FOR CountType IN ( [TotalCustomer], [NotCalled] ) ) AS pvt