2011-03-25 45 views
0

我需要从两个表中选择计数,这两个表共享一个公共列,即clientId,并将总数除以clientIds,给定日期和dateadded列在这两个表中都是日期时间格式。sql server - 从报表的两个表中获取计数和列值

例如,测试结果将显示:

ClientId  Total1 Total2 
aaaa   1  2 
bbbbb   43  45 
ccccc   123 355 

等为2011-03-25

我目前拥有的是

select 
    (select clientid,count(*) as total1 from TFeed where dateadded = getdate() 
    group by clientId), 
    (select clientId, count(*) as total2 from WFeed where dateadded = getdate() 
    group by clientid) 

这当然是错误的。 错误:子查询未与EXISTS一起引入时,只能在选择列表中指定一个表达式。此外,为了考虑,这些表格非常大 - 超过300万条记录并不断增长。任何帮助表示赞赏

编辑:

了时间 - 如果dateadded = '2011-03-25 12时零零分34秒0011',我哪有时间比较 GET dateadded = @getdate()和选择今天的所有记录。

虽然我的查询仍在运行 - 关闭主题问题...因为这是一个报告查询,我想定期运行它来更新总数,以便当客户端打开网页或点击报告时,它将提供总计而无需运行查询并从数据库中选择最后的总计。那么我需要有一个不同的查询或每隔一小时左右运行一次。

回答

1

你很近。在进行汇总之前,您希望将两个表格连接在一起

select 
    clientid, 
    sum(case when t.clientid is not null then 1 else 0 end) as total1 
    sum(case when w.clientid is not null then 1 else 0 end) as total1 
    from TFeed t FULL OUTER JOIN WFeed w 
    where w.dateadded = getdate() or t.dateadded = getdate() 

这可能不完全符合您的要求,但这是一般想法。这也处理了特定日期的某个表中没有数据的情况。

+0

感谢执行它但它仍然在运行 - 采取这么长的时间......差不多一个小时......就像我说的那样,在这两个表中大约有4百万条记录 – vbNewbie 2011-03-25 17:34:44

+0

你有没有关于clientid的指示? – dfb 2011-03-25 17:39:51

+0

对不起没有客户IdI – vbNewbie 2011-03-25 17:46:58

1
select tf.clientid, 
     SUM(case when tf.dateadded = getdate() then 1 else 0 end) as Total1, 
     SUM(case when wf.dateadded = getdate() then 1 else 0 end) as Total2 
from tfeed tf full outer join wfeed wf on tf.clientid = wf.clientid 
group by tf.clientid 
+1

内部连接将消除不在两个表中的记录。另外,您构建查询的方式将迭代所有评估case语句的记录,并进行总和并忽略不落入日期条件的记录。 – DidierDotNet 2011-03-25 16:40:13

+0

@DidierDotNet - 是的,你是对的。编辑。 – 2011-03-25 16:41:53

+0

谢谢,但内部连接不会正常工作 – vbNewbie 2011-03-25 17:32:58

0

尝试一下这样的事情。

select clientid, sum(total1) as total1, sum(total2) as total2 
from 
(select clientid,count(*) as total1, 0 as total2 
from TFeed 
where dateadded = @someDate 
group by clientId 
UNION 
select clientId, 0 as total1, count(*) as total2 
from WFeed 
where dateadded = @someDate 
group by clientid) 
group by clientid 
0

使用交叉应用真的很有帮助,并且显着加快速度。我对你的关联并不积极,你的2个提要中的客户端ID是否有一对一的关系,但这是你想要针对这么多记录优化查询的方向。

而且,这里是另一个讨论的链接与交叉的主题的更多信息,适用,如果这个确切的查询是不适合你的工作可能会有所帮助:

When should I use Cross Apply over Inner Join?

with x as (
    select clientID as clientID, COUNT(*) as total1 
    from TFeed where dateadded = GETDATE() 
    group by clientID 
    ) 
    select x.clientID,x.total1,y.total2 from x 
    cross apply 
    (
     select clientID as clientID, COUNT(*) as total2 
     from WFeed where dateadded = GETDATE() 
     group by clientID 
    ) y 
相关问题