2016-06-24 2 views
0

두 테이블이 있고 CTE에서 원하는 결과를 얻었으며 CTE 쿼리 후에 바로 다음 결과를 얻었습니다.CTE 직후 쿼리에 의해 만들어진 PIVOT 결과 집합

[Lead_Created_Month] 열에 의해 결과 세트를 피벗하는 방법에 대한 유일한 부분은 확실하지 않습니다. 결과 집합을 하위 쿼리로 랩핑하고 별칭을 지정해야하지만 정확히 어떻게 처리해야하는지 잘 알고 있어야합니다. 이 코드는 원하는 결과 세트를 생성하는 데 적합하지만이 결과 세트는 [Lead_Created_Month] 열에 의해 피벗되어야합니다. Current result sent

최종 결과 집합은 다음과 같아야합니다 :

final result set

당신이 내 코드의 계산 누락 볼 수 있듯이

USE DatabaseName 
GO 
Create Table #TempSales 
(
LeadID_fk int identity (1,1), 
[dateCreated] datetime 
) 

insert into #TempSales 
values 
(NULL), 
(getdate()), 
(getdate()), 
(NULL), 
(getdate()), 
(getdate()), 
(getdate()), 
(NULL), 
(getdate()), 
('2016-05-24 14:17:41.330'), 
('2016-03-24 14:17:41.330'), 
('2016-03-22 14:17:41.330'), 
('2016-03-21 14:17:41.330'), 
('2016-04-24 14:17:41.330'), 
(NULL); 

Create Table #TempLead 
(
LeadID int identity (1,1), 
[dateCreated] datetime 
) 

insert into #TempLead 
values 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
(getdate()), 
('2016-05-24 14:17:41.330'), 
('2016-03-24 14:17:41.330'), 
('2016-03-22 14:17:41.330'), 
('2016-03-21 14:17:41.330'), 
('2016-04-24 14:17:41.330'), 
(getdate()); 
Select * from #TempLead; 
Select * from #TempSales 

;with cte 
as 
(Select * from #TempLead) 
select count(l.LeadID) as [count of Leads], count(s.LeadID_fk) as [count of Sales], 
Cast(datepart(mm,[l].[dateCreated]) as varchar(2))+'/'+ 
--Cast(datepart(dd,[dateCreated]) as varchar(3))+'/'+ 
Cast(datepart(yyyy,[l].[dateCreated]) as varchar(5)) as [Lead_Created_Month] 
from cte as l 
    left join #TempSales as s on s.LeadID_fk=l.LeadID 
    and s.[dateCreated] is not null 
    group by Cast(datepart(mm,[l].[dateCreated]) as varchar(2))+'/'+ 
    Cast(datepart(yyyy,[l].[dateCreated]) as varchar(5)) 

위의 쿼리는 다음과 같은 출력을 반환 전환율.

그래서 나는 그것을 계산하는 코드 작성 :

--,Cast((Select count([s].LeadID_fk) from #TempSales as s where [s].[dateCreated] is not null 
--/* group by Cast(datepart(mm,[s].[dateCreated]) as varchar(2)) +'/'+ Cast(datepart(yyyy,[s].[dateCreated]) as varchar(5)) */ 
--)/count([l].LeadID) *100 as nvarchar(10)) + '%' as Conversion 

을하지만이 올바른지 SSMS에 표시하기 위해이 경고 메시지가 나타납니다. 그것은 단지 더 나은 해결책을 모르고 있습니다.

메시지 레벨 512, 수준 16, 상태 1, 줄 1 하위 쿼리는 1보다 큰 값을 반환했습니다. 하위 쿼리가 =,! =, <, < =,>>,> = 또는 하위 쿼리가 식으로 사용될 때 하위 쿼리가 수행되는 경우에는 허용되지 않습니다.

답변

1

필자는 피벗을 사용하려는 경우 이와 같이해야한다고 생각합니다. yyyymm을 하드 코딩하지 않으려면 동적 SQL을 사용해야합니다.

;with cte as 
(
select 1 as srce,year(tl.dateCreated) *100 + month(tl.dateCreated) as yyyymm,count(*) as leadcount 
from #templead tl 
group by year(tl.dateCreated) *100 + month(tl.dateCreated) 
union all 
select 2 as srce,year(ts.dateCreated) *100 + month(ts.dateCreated) ,count(*) as leadcount 
from  #tempsales ts 
group by year(ts.dateCreated) *100 + month(ts.dateCreated) 
) 
select case 
      when t.srce = 1 then 'leads' 
      when t.srce = 2 then 'sales' 
      when t.srce = 3 then 'comversions' 
      end as ' ' 
      ,t.[201603],t.[201604],t.[201605],t.[201606] 
from 
(
select pvt.* from 
(
select 1 srce,year(tl.dateCreated) *100 + month(tl.dateCreated) as yyyymm,1 as leadcount 
from #templead tl 
) s 
pivot (sum(s.leadcount) for s.yyyymm in ([201603],[201604],[201605],[201606])) pvt 
union all 
select pvt.* from 
(
select 2 srce,year(ts.dateCreated) *100 + month(ts.dateCreated) as yyyymm,1 as leadcount 
from #tempsales ts 
) s 
pivot (sum(s.leadcount) for s.yyyymm in ([201603],[201604],[201605],[201606])) pvt 
union all 
select * from 
(
select 3 srce,c1.yyyymm,cast(cast(c2.leadcount as decimal (10,5))/cast(c1.leadcount as decimal(10,5)) * 100 as int) as conversion 
from cte c1 
join cte c2 on c1.yyyymm = c2.yyyymm and c2.srce = 2 
where c1.srce = 1 
) s 
pivot (max(s.conversion) for s.yyyymm in ([201603],[201604],[201605],[201606])) pvt 
) t 
+0

고마워요. 변환 PIVOT 출력에서 ​​캐스트 또는 변환을 사용하려면 어떻게해야합니까? 위 코드의 마지막 두 줄입니다. ([201603], [201604], [201605], [201606]))의 s.yyyymm에 대한 pivot (max (s.conversion)) pvt ) t; – enigma6205

+0

당신은 case 문을 추가 할 수 있습니다 같은 \t \t 경우와 \t \t \t t.srce = 3 다음 캐스트 (t. [201603] VARCHAR (최대)로) '%'를 + \t \t \t 다른 캐스트 (t. 201603 ]으로 varchar (max)) \t \t \t 끝은 [201603]와 같이 cte 정의 직후에 선택합니다 –