带组的SQL Pivot数据

时间:2018-11-08 12:57:12

标签: sql linq pivot

我有这个查询:

 SELECT TOP (1000) count([CallId]) as totalCalls
      ,[CallDirection]
      ,[AssignedWorkGroup]
      ,DATEPART(month, connectedDate) as SelectedMonth
 FROM [mydatabase].[dbo].[calldetail_viw]
 where connectedDate > '2018-8-01'
 and localname='myaccountrep'
 and AssignedWorkGroup <>'-'
 group by assignedworkgroup,calldirection,DATEPART(month, connectedDate) 
 order by SelectedMonth,calldirection

它将在列

中返回我的数据
totalcalls, calldirection, assigned workgroup, selectedmonth

但是我需要我的数据

SelectedMonth, Assignedworkgroup, INBOUND, OUTBOUND, TotalCalls

所以我需要在calldirection字段中旋转两个值。有人可以告诉我如何修改查询吗? 我实际上在LINQ中需要它。 TIA!

1 个答案:

答案 0 :(得分:1)

有条件的聚合看起来可以解决问题。

类似的事情...

SELECT
  selectedMonth,
  AssignedWorkgroup,
  SUM(CASE WHEN calldirection =  'INBOUND' THEN totalCalls ELSE 0 END)   AS INBOND,
  SUM(CASE WHEN calldirection = 'OUTBOUND' THEN totalCalls ELSE 0 END)   AS OUTBOND,
  SUM(totalCalls)                                                        AS totalCalls
FROM
(
  <yourquery>
)
  AS toPivot
GROUP BY
  selectedMonth,
  assignedWorkgroup