我运行的查询返回tableau中不允许的同一列中的2,并且我无法修复该查询

时间:2019-06-12 14:29:09

标签: sql sql-server tableau

我需要能够摆脱工作日期之一和sr_name列之一,但我不知道该怎么做。

我正在返回查询,如下所示: Query

输入到Tableau中时,我还会收到此错误消息:

   The column 'sr_name' was specified multiple times for 'Custom SQL Query'.

下面是我的代码。如果我从任何一个子查询中删除了一个sr_name,则join子句中将出现错误。

select * 
from
(
select s.sr_name, cast(punchdatetime as date) as workdate,
    ((datediff(second, min(case when p.InOut = 1 then punchdatetime end), 
    max(case when p.InOut = 0 then punchdatetime end))/3600) - .5) as 
    hoursworked
    from PunchClock p join ServiceReps s on p.ServRepID = s.ServRepID
    where punchyear >= 2019
    group by s.sr_name, cast(punchdatetime as date)
    ) v

join 
    (
    select sr_name, t.*,
    calls = (select count(*) from CRM_Correspondence cr where 
    cast(cr.DateCreated as date) = workdate and StatusType like '%call%' and 
    cr.ServRepID = t.servrepid),
    reaches = (select count(*) from CRM_Correspondence cr where 
    cast(cr.DateCreated as date) = workdate and (StatusType = 'call reached' 
    or StatusType like '%SCHEDULE%') and cr.ServRepID = t.servrepid),
    books = (select count(*) from os_appointments o where cast(o.DateCreated 
    as date) = workdate  and isnull(o.confirmedby, o.booked_by) = 
    t.servrepid),
    attends = (select count(*) from os_appointments o where 
    cast(o.DateCreated as date) = workdate  and isnull(o.confirmedby, 
    o.booked_by) = t.servrepid and o.appointmentStatus = 'attended')

from
    (
    select cast(cor.datecreated as date) workdate, cor.ServRepID
    from CRM_Correspondence cor
    where cor.datecreated > '2019-01-01'
    group by cast(cor.datecreated as date), cor.servrepid
    ) t
join ServiceReps sr on t.ServRepID = sr.ServRepID
) u on v.sr_name = u.sr_name and v.workdate = u.workdate

我需要相同的结果,只是没有重复的列,因此我可以将查询输入到tableau中。

1 个答案:

答案 0 :(得分:2)

这很有挑战性,因为您在这里有很多子查询。这可以重构为使用单个查询,这就是我要做的。但是,使用现有查询,您可以按照以下方式进行操作。

我必须对这种格式进行非常不同的格式化,以便我可以隔离每一个。

library(data.table)
DT[, DT_med := median(unlist(.SD), na.rm = TRUE), by = file]