SQL矩阵查询

时间:2013-06-04 14:21:55

标签: sql matrix count subquery

我每个月都要尝试返回一些事件。

我有一张桌子,有3列;回调,跟进,服务。我想要做的是返回每个月每个事件发生一次帐户的次数。

我试图使用子查询:

Select...<columns>...
(
    select 
    COUNT(eventname)
    from 
    tworkorderevent 
    group by eventname
    having 
    eventname = 'Follow up'
)FollowUps,
from <tablename>
where...
group by ...

但这仅返回事件的总数,而不是每月每个帐户的数量。

我们很高兴收到任何有关清晰度的建议或要求。谢谢。

1 个答案:

答案 0 :(得分:0)

你应该能够做到这一点:

Select a.account_id, b.follow_up_count, c.callback_count, d.service_count
From tworkorderevent a
Left Outer Join
(
    select account_id, COUNT(eventname) as follow_up_count
    from tworkorderevent
    where eventname like 'Follow up'
    group by account_id
)b On a.account_id = b.account_id
Left Outer Join
(
    select account_id, COUNT(eventname) as callback_count
    from tworkorderevent
    where eventname like 'Callback'
    group by account_id
)c On a.account_id = c.account_id
Left Outer Join
(
    select account_id, COUNT(eventname) as service_count
    from tworkorderevent
    where eventname like 'Service'
    group by account_id
)d On a.account_id = d.account_id

只需将“account_id”引用替换为您的主键,并确保每个“Where”语句的值都正确。