合并单独的查询

时间:2014-06-25 13:22:35

标签: sql sql-server group-by

我有这四个单独的查询,我想要合并到一个结果集中,我不太清楚如何做到这一点。基本上,我希望看到包含以下列的单个输出:

name - items_created - items_modified - copies_created - copies_modified

select t02CreatedBy as name, count(t02CreatedBy) as items_created
from dbo.Items_t02
where t02DateCreated > getdate() - 7
group by t02CreatedBy

select t02ModifiedBy as name, count(t02ModifiedBy) as items_modified
from dbo.Items_t02
where t02DateModified > getdate() - 7
group by t02ModifiedBy

select t03CreatedBy as name, count(t03CreatedBy) as copies_created
from dbo.Copies_t03
where t03DateCreated > getdate() - 7
group by t03CreatedBy

select t03ModifiedBy as name, count(t03ModifiedBy) as copies_modified
from dbo.Copies_t03
where t03DateModified > getdate() - 7
group by t03ModifiedBy

对我来说,棘手的部分是理解如何在保持各种分组的同时将它们结合起来。我需要确保t02DateCreated与t02CreatedBy相关联,并且t02DateModifed与t02ModifiedBy(等等...)相关联。不确定如何在一个查询中执行此操作。

有什么建议吗?或者我是以错误的方式解决这个问题?

2 个答案:

答案 0 :(得分:1)

将select语句更改为包含类似

的内容
select **'Query 1' as Type**, t03ModifiedBy as name, count(t03ModifiedBy) as          copies_modified
from dbo.Copies_t03
where t03DateModified > getdate() - 7
group by t03ModifiedBy

然后在每个查询之间添加“全部联盟”。

答案 1 :(得分:0)

嗯,这是一种你仍然可以在SQL服务器上做的方式(我还没有测试过):

SELECT name,
      (select count(t02CreatedBy) from dbo.Items_t02
       where t02DateCreated>getdate()-7 and t02CreatedBy=name) createdItems
      (select count(t02ModifiedBy) from dbo.Items_t02
       where t02DateModified>getdate()-7 and t02ModifiedBy=name) modifiedItems
      (select count(t03CreatedBy) from dbo.Copies_t03
       where t03DateCreated>getdate()-7 and t03CreatedBy=name) createdCopies
      (select count(t03ModifiedBy) from dbo.Copies_t03
       where t03DateModified>getdate()-7 and t03ModifiedBy=name) modifiedCopies
FROM (    select t02CreatedBy name FROM dbo.Items_t02
union all select t02ModifiedBy     FROM dbo.Items_t02
union all select t03CreatedBy      FROM dbo.Copies_t03
union all select t03ModifiedBy     FROM dbo.Copies_t03   ) 
allnames GROUP BY name

外部(分组)查询会收集所有可能的name,因为它们可能会出现在t02CreatedBy,t02ModifiedBy, t03CreatedByt03ModifiedBy四列中的任何一列中。然后,它使用四个子查询将相关表中每个列的计数汇总在一起。

由于我不知道您的数据,我在外部查询中使用了UNION ALL - 构造。如果您可以保证其中一列(例如t02ModifiedBy)实际包含“所有可能”的名称,那么在那里单独使用该列也可以,例如:

...
FROM t02ModifiedBy FROM dbo.Items_t02 GROUP BY name