请求在SQL Server 2005中使用GROUP BY子句加入其他两个请求的结果

时间:2009-08-19 16:08:23

标签: sql sql-server sql-server-2005

我经常发现自己在sql server 2005中执行以下操作:

第1步:

create view view1 as 
select count(*) as delivery_count, clientid from deliveries group by clientid;

第2步:

create view view2 as 
select count(*) as action_count, clientid from routeactions group by clientid;

第3步:

select * from view1 inner join view2 on view1.clientid = view2.clientid

是否可以仅在一个语句中获得相同的最终结果,从而避免创建视图?

3 个答案:

答案 0 :(得分:4)

当然,使用嵌套查询:

select *
from (select count(*) as delivery_count, clientid 
      from deliveries group by clientid) AS view1
inner join (select count(*) as action_count, clientid
            from routeactions group by clientid) AS view2
    on view1.clientid = view2.clientid

或者使用新的CTE语法,您可以:

WITH view1 AS (
    select count(*) as delivery_count, clientid from deliveries group by clientid
), view2 AS (
    select count(*) as action_count, clientid from routeactions group by clientid
)
select * from view1 inner join view2 on view1.clientid = view2.clientid

答案 1 :(得分:0)

除非在你没有提及的路线和交付之间存在某种关系,否则我无法想到任何方式。没有它(很可能是从一个到另一个的FK),你不能在不扭曲一个或两个表上的数字的情况下进行连接。

答案 2 :(得分:0)

SELECT
    clientid,
    (SELECT COUNT(*) FROM deliveries where clientid = clientIds.clientid) AS 'delivery_count',
    (SELECT COUNT(*) FROM routeactions WHERE clientid = clientIds.clientid)
AS 'action_count'
FROM
(
SELECT clientid FROM deliveries
UNION
SELECT clientid FROM routeactions
) clientIds

我相信这应该有效,如果你有一个客户表

,有更简单的解决方案