SQL Query Merge 2 into 1

时间:2017-03-09 19:34:27

标签: sql

如何将下面的2个查询合并为1,第4列计算列数2和3之间的百分比

Select DISTINCT ASSN, COUNT(REAPING_GROUP_CODE) as TotalGroups
FROM ReapingGroups
GROUP BY ASSN
Order by ASSN


Select  ASSN, COUNT(REAPING_GROUP_CODE) as Groups
FROM ReapingGroups
WHERE  EXISTS (Select * FROM DeliveryTons where reaping_code = REAPING_GROUP_CODE AND remarks = '')
GROUP BY ASSN

2 个答案:

答案 0 :(得分:1)

这里有点黑客攻击,但它应该能为你提供你想要的东西:

select ASSN, sum(TotalGroups) as TotalGroups, sum(CAST(Groups AS DECIMAL)) / sum(CAST(TotalGroups AS DECIMAL))*100.00 as Percentage
from
(
  (
   Select DISTINCT ASSN, COUNT(REAPING_GROUP_CODE) as TotalGroups, 0 as Groups
   FROM ReapingGroups
   GROUP BY ASSN
  )
  union all    
  (
    Select  ASSN, 0 as TotalGroups, COUNT(REAPING_GROUP_CODE) as Groups
    FROM ReapingGroups
    WHERE  EXISTS (Select * FROM DeliveryTons where reaping_code = REAPING_GROUP_CODE AND remarks = '')
    GROUP by ASSN
  )
) NamedSubQuery
group by ASSN
order by ASSN;

答案 1 :(得分:0)

我不会尝试编写一个具体的例子,因为在撰写本文时您还没有显示任何样本数据或任何内容,但这里可以使用一般技术来组合条件计数和无条件计入单个查询:

select 
    FieldName,
    count(1) -- Unconditional count
    sum(case when /*condition*/ then 1 else 0 end) -- Conditional count
from 
    TableName
group by
    FieldName;

另外,请稍等:第一个查询中的DISTINCT是多余的,因为您已经在同一个字段上进行分组,这足以保证每个唯一ASSN值得到结果集中只有一条记录。