使用连接返回针对相同查询的结果的查询结果

时间:2016-06-23 13:22:20

标签: sql

我正在努力将其写成文字,因此标题不好;

我想返回一个查询的结果以及连接到另一个表的同一查询内部的结果(因此,value1的总数与另一个表中显示的value1的数量相对应)。所以我想返回以下查询的每个所有者的计数;

SELECT DISTINCT(Owner), COUNT(Owner) FROM Actions
INNER JOIN [DataCapture].[dbo].DataCapture ON Actions.Contact_ID = DataCapture.ID 
GROUP BY Owner ORDER BY Owner

然后我想从总数中找出百分比;

SELECT DISTINCT(Owner), COUNT(Owner) FROM Actions 
GROUP BY Owner ORDER BY Owner

我认为INTERSECT或EXCEPT就是这样,但由于我返回了不同的计数,因此效果不佳。

编辑:为清楚起见,第一次和第二次查询的结果分别如下;

USER1   212
USER2   613
USER3   155
USER4   375
USER5   8
USER6   76



USER1     1218
USER2     849
USER3     237
USER4     1062
USER5     39
USER6     418

所以我想要的是,在1个查询中,第一个查询的结果对第二个查询的结果给出了百分比。

3 个答案:

答案 0 :(得分:1)

你可以用CTE(我猜你正在使用Sql Server)或内部查询来做到这一点

select a.Owner, count(*), totalActions, (count(*) * 1.0 / totalActions) * 100 as yourpercentage
from Actions a
join DataCapture db on db.Id = a.Contact_Id
join (select Owner, count(*) as totalActions from Actions
      group by Owner) total on total.Owner = a.Owner
group by a.Owner, total.totalActions

顺便说一句

,无需与group by区分开来

答案 1 :(得分:0)

SELECT 
       ACTIONS_BY_DATACAP.Owner AS OWNER, 
       (ACTIONS_BY_DATACAP.Cnt/TOT_ACTIONS_BY_USR.TotCnt)*100 AS PERCENTAGE 
FROM
(
 SELECT DISTINCT(Owner) as Owner, COUNT(Owner) as Cnt FROM Actions
 INNER JOIN [DataCapture].[dbo].DataCapture ON Actions.Contact_ID =  
 DataCapture.ID 
 GROUP BY Owner ORDER BY Owner
) AS ACTIONS_BY_DATACAP
INNER JOIN 
(
SELECT DISTINCT(Owner), COUNT(Owner) as TotCnt FROM Actions 
GROUP BY Owner ORDER BY Owner
) AS TOT_ACTIONS_BY_USR
ON TOT_ACTIONS_BY_USR.Contact_ID =  
 ACTIONS_BY_DATACAP.ID 

答案 2 :(得分:0)

CTE示例能为您提供所需的信息吗?

;WITH q1 as
(SELECT Owner, COUNT(Owner) c1 FROM Actions
INNER JOIN [DataCapture].[dbo].DataCapture ON Actions.Contact_ID = DataCapture.ID 
GROUP BY Owner),
q2 as
(SELECT Owner, COUNT(Owner) c2
FROM Actions 
GROUP BY Owner)

SELECT
     q1.Owner, q1.c1, q2.c2, q1.c1/q2.c2 percentage
FROM
    q1
JOIN
    q2 ON q1.Owner = q2.Owner
ORDER BY 
   Owner