如何根据月度和年度客户报告来透视数据

时间:2018-09-01 06:55:32

标签: sql-server

我正在尝试根据每年的月份检索数据。会得到,但排序不正确。

SELECT Client,DispacthDate,Models,Model1,Model2,Model3
FROM  (
        SELECT  Client
                ,Concat(year(Audit_Date),' ',datename(month,Audit_Date)) as DispatchDate
                ,Models
                ,Count(Models) 'Units'
        FROM dbo.ABC
        GROUP BY Client,Concat(year(Audit_Date),' ',datename(month,Audit_Date)),Models
      ) abcd
PIVOT(SUM(Units) FOR Models IN (Model1,Model2,Model3)) as P
ORDER BY Client,DispatchDate

我将得到如下结果集:

 
Client  DispatchDate    Model1  Model2  Model3
Client1 2017 December   0   0   0
Client1 2017 November   25  0   0
Client1 2018 January    21  0   0
Client1 2018 March       9  0   0
Client2 2017 December    8  0   0
Client2 2018 April       5  0   0
Client2 2018 August      0  0   0
Client2 2018 July        0  0   0
Client2 2018 March       0  0   0
Client3 2017 December    4  0   0
Client3 2017 November   687 0   0
Client3 2018 April       8  0   0
Client3 2018 January     0  0   0


但必填数据,例如:

Client  DispatchDate    Model1  Model2  Model3
Client1 2018 January    21  0   0
Client1 2018 March       9  0   0
Client1 2017 November   25  0   0
Client1 2017 December   0   0   0
Client2 2018 March      0   0   0
Client2 2018 April      5   0   0
Client2 2018 July       0   0   0
Client2 2018 August     0   0   0
Client2 2017 December   8   0   0
Client3 2018 January    0   0   0
Client3 2018 April      8   0   0
Client3 2017 November   687 0   0
Client3 2017 December   4   0   0

请有人建议我查询。

2 个答案:

答案 0 :(得分:0)

在内部查询中不要将DispatchDate转换为字符串。将其保留为日期或日期时间类型。然后在外部查询处将其转换

SELECT Client,
       DATENAME(YEAR, Audit_Date) + ' ' + DATENAME(MONTH, Audit_Date) AS DispatchDate,  
       Models, Model1, Model2, Model3
FROM  (
        SELECT  Client
                ,DATEADD(MONTH, DATEDIFF(MONTH, 0, Audit_Date), 0) as Audit_Date
                ,Models
                ,Count(Models) AS Units
        FROM    dbo.ABC
        GROUP BY Client, 
                 DATEADD(MONTH, DATEDIFF(MONTH, 0, Audit_Date), 0), month(Audit_Date)),
                 Models
      ) abcd
PIVOT(SUM(Units) FOR Models IN (Model1,Model2,Model3)) as P
ORDER BY Client, Audit_Date

答案 1 :(得分:0)

据我了解

SELECT Client,DispacthDate,Models,Model1,Model2,Model3
FROM  (
        SELECT  Client
                ,Concat(year(Audit_Date),' ',datename(month,Audit_Date)) as DispatchDate
                ,Models
                ,Count(Models) 'Units'
        FROM dbo.ABC
        GROUP BY Client,Concat(year(Audit_Date),' ',datename(month,Audit_Date)),Models
      ) abcd
PIVOT(SUM(Units) FOR Models IN (Model1,Model2,Model3)) as P
ORDER BY Client,
, DATEPART (YYYY, convert(date, DispacthDate)) desc  -- here query has been changed.
, DATEPART (MM, convert(date, DispacthDate))  -- here query has been changed.