2016-09-21 72 views
0

我有点复杂的查询....我需要做一个关于两个联合SQL查询求和的更新语句(问题是查询中的数据不是数字所以我计算行而不是总结值),但我需要总结这些行。SQL Union计数到总和数据

UPDATE #LT_Actuals_TEMP 
SET  pCount = h.countPerfs 
FROM (
select count(distinct c.perf_description) as countPerfs, b.program, b.Prog_id 
from #LT_Actuals_TEMP TableP 
where  a.Performances = 'Y' and a.current_inactive = 0 
group by b.Program, b.Prog_id 
union 
select distinct count(p.perf_code) as countPerfs, x.value, b.Prog_id 
from T_PERF p  
where x.content_type = 23 
group by x.value, b.Prog_id 
) h where h.Prog_id = #LT_Actuals_TEMP.program_id 

第一查询数据回来这样

countPerfs program Prog_id 
7   Name  31 

和第二查询回来为

countPerfs program Prog_id 
1   Name  31 

什么,我需要pCount在一天结束的时候将被设置为8

预期结果
w母鸡我做select * from #LT_Actuals_TEMP 我看到价值 8的程序名称,标识31

+0

请发布您的预期结果 – TheGameiswar

+0

发布/调整! – YelizavetaYR

+0

此外,您还拿出了一堆代码中的'... \',但这是为了显示一个大型的复杂查询,它不像上面那么简单。但只要清楚发生了什么,我就会很好。 – YelizavetaYR

回答

1

你可以解决它通过从那里你总结的数据从工会返回部分将在另一个层面。

您的查询似乎缺少一些源表(因为有使用别名不指向任何东西),所以我想你是去掉了一些部件,但在总体上应该是这个样子:

UPDATE #LT_Actuals_TEMP 
SET  pCount = h.sum_of_countperfs  
FROM (
    select program, prog_id, sum(countPerfs) as sum_of_countperfs 
    from (
    select count(distinct c.perf_description) as countPerfs, b.program, b.Prog_id 
    from #LT_Actuals_TEMP TableP 
    where  a.Performances = 'Y' and a.current_inactive = 0 
    group by b.Program, b.Prog_id 
    union all 
    select distinct count(p.perf_code) as countPerfs, x.value, b.Prog_id 
    from T_PERF p  
    where x.content_type = 23 
    group by x.value, b.Prog_id 
) as sub_q group by program, prog_id 
) h where h.Prog_id = #LT_Actuals_TEMP.program_id 

另外,您可能要使用union all,以避免重复项被删除。

+0

林很抱歉有些困惑,但我很难理解什么是加入这里解决问题。 – YelizavetaYR

+0

@YelizavetaYR我试图更好地格式化它,以便更容易看到添加。我将原始联合查询包装在一个汇总数据的外部查询中。 – jpw

+0

啊我得到了这个概念,你增加了一个额外的等级。你在选定的一个级别中汇总/汇总了我的数据,然后进行更新 – YelizavetaYR