【发布时间】:2016-06-24 20:51:15
【问题描述】:
我有两个表,我从 CTE 获得了所需的结果,并在 CTE 查询后立即跟进。
我不确定如何通过 [Lead_Created_Month] 列旋转结果集的唯一部分。我可能需要将结果集包装到一个子查询中并给它一个别名,但不确定具体如何。这是我的代码,可以很好地生成所需的结果集,但是这个结果集需要由 [Lead_Created_Month] 列进行透视。
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 个 > 值。当子查询跟随 =、!=、 >、>= 或子查询用作表达式时,这是不允许的。
【问题讨论】:
标签: sql-server subquery pivot common-table-expression