我有一个查询,它返回有关工作板的分析样式信息以及申请人来自以下结构的位置:
要访问的查询是:
SELECT g.name AS [Source]
,SUM(CASE WHEN v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Clicks]
,SUM(CASE WHEN v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Clicks]
,COUNT(v.id) AS [Total Clicks]
,SUM(CASE WHEN a.applicant = 1 AND v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Applicants]
,SUM(CASE WHEN a.applicant = 1 AND v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Applicants]
,SUM(CASE WHEN a.applicant = 1 THEN 1 ELSE 0 END) AS [Total Applicants]
,SUM(v.cost/100.0) AS [Spend]
FROM a_views v
LEFT OUTER JOIN a_views a
ON v.viewerid = a.viewerid
AND v.sessionsourceid = a.sessionsourceid
AND a.applicant = 1
JOIN a_sources s
ON v.sourceid = s.id
JOIN a_sourcegroups g ON s.fk_sourcegroup = g.id
--JOIN jobs j ON v.jobid = j.anal_id AND j.featured = 1
WHERE v.hostName = @jobboard
AND v.viewed_at >= @start AND v.viewed_at <= @end
GROUP BY g.name
唯一的问题是在LEFT OUTER JOIN a_views
块中可能会返回多个记录。我需要做的只是在Click
总和中跟踪记录一次,但每次在Applicant
总和中找到记录。
我确实在this question上发现了类似的问题,但回答者实际上没有提供太多信息。
要重新填充我需要的内容,连接右侧的每个记录实例,但左侧只有1个记录实例。
答案 0 :(得分:0)
您可以在不完全更改查询的情况下执行此操作的一种方法是将点击总和和申请人总和分成两个单独的查询,UNION
将它们放在一起,然后再对它们进行分组/求和。
像这样(伪代码):
SELECT
Source
,SUM([Organic Clicks])
,.....
FROM
(
SELECT g.name AS [Source]
,SUM(CASE WHEN v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Clicks]
,SUM(CASE WHEN v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Clicks]
,COUNT(v.id) AS [Total Clicks]
,0 AS [Organic Applicants]
,0 AS [Paid Applicants]
,0 AS [Total Applicants]
,SUM(v.cost/100.0) AS [Spend]
FROM
ClickOnlyTables
UNION ALL
SELECT g.name AS [Source]
,0 AS [Organic Clicks]
,0 AS [Paid Clicks]
,0 AS [Total Clicks]
,SUM(CASE WHEN a.applicant = 1 AND v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Applicants]
,SUM(CASE WHEN a.applicant = 1 AND v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Applicants]
,SUM(CASE WHEN a.applicant = 1 THEN 1 ELSE 0 END) AS [Total Applicants]
,0 AS [Spend]
FROM
ApplicantTables
)
GROUP BY
Source
答案 1 :(得分:0)
出于某种原因,我认为你不想要自我加入来回答这个问题。也许只是聚合a_views一次解决问题,首先是申请人,然后是游戏。
我发现很难从你的查询中确定你想要的东西,但这样的东西是第一个聚合:
select g.name, valuationDups.viweerid, v.sessionsourceid,
SUM(CASE WHEN v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Clicks],
SUM(CASE WHEN v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Clicks],
COUNT(v.id) AS [Total Clicks],
SUM(CASE WHEN a.applicant = 1 AND v.cost = 0 THEN 1 ELSE 0 END) AS [Organic Applicants],
SUM(CASE WHEN a.applicant = 1 AND v.cost <> 0 THEN 1 ELSE 0 END) AS [Paid Applicants],
SUM(CASE WHEN a.applicant = 1 THEN 1 ELSE 0 END) AS [Total Applicants],
SUM(v.cost/100.0) AS [Spend]
FROM a_views v JOIN
a_sources s
ON v.sourceid = s.id JOIN
a_sourcegroups g
ON s.fk_sourcegroup = g.id
WHERE v.hostName = @jobboard and
v.viewed_at >= @start AND
v.viewed_at <= @end
group by g.name, valuationDups.viweerid, v.sessionsourceid
然后再通过g.name聚合。