需要T-SQL查询UNION,JOINS,COUNT

时间:2016-12-11 18:05:10

标签: sql sql-server tsql

看起来我厌倦了查询以汇总由工会运营商分组的货件。今天我正在努力检索由代理商,司机(U.AgentCode)交付到特定国家(U.CtryCode,U.CtryName)的总出货量(计数(Distinct .USDjipmentId)。我想做的最后一件事是将所有货物汇总在一起以获得总发货量。 有人会建议我如何通过简单方便的方式实现这一目标吗?  您可以在下面找到我最新的查询。

SELECT U.AgentCode, U.CtryCode, U.CtryName, count(distinct U.Id)
    FROM (
    select Agent.AgentCode, Addr.CtryCode, Ctry.Name, Ship.Id
    from Shipment
    LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.ID  
    LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = RouteTbl.AgentID
    LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
    LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
    WHERE RouteTbl.Bur ='GB01' AND Agent.AgentCode IS NOT NULL
    Union ALL
    select Driver.DriverCode, Addr.CtryCode, Ctry.Name, Shipment.Id
    from Shipment
    LEFT JOIN RouteTab (nolock) ON RoutTbl.Cexp= Shipment.Id
    LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = RouteTbl.DriverId
    LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
    LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
    WHERE RouteTbl.Bur ='GB01' AND Driver.DriverCode IS NOT NULL
    )  as U 
GROUP BY U.AgentCode, U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName

2 个答案:

答案 0 :(得分:0)

Union语句需要具有完全相同的列名,在Union All命令下面的代码中,请尝试:

select Driver.DriverCode as AgentCode, Addr.CtryCode, Ctry.Name, Shipment.Id

同时在两个select语句中将Ctry.Name更改为Ctry.Name as CtryName

答案 1 :(得分:0)

您的UNION代码相同。使用WITH子句的好方法。 在select中,您不需要UNION - 请使用左连接和COALESCE

;With r_tab AS
(
select RouteTab.AgentID, Addr.CtryCode, Ctry.Name, Ship.Id,RouteTab.DriverId
    from Shipment
    LEFT JOIN RouteTab (nolock) ON RouteTab.Cexp= Shipment.ID 
    LEFT JOIN Addr (NOLOCK) ON Addr.AddrId = Shipment.AddrId
    LEFT JOIN Ctry (NOLOCK) ON Ctry.Id = Addr.Id
    WHERE RouteTab.Bur ='GB01'
)
SELECT COALESCE(Agent.AgentCode,Driver.DriverCode) AgentCode, U.AgentCode, U.CtryCode, U.CtryName,
       count(distinct U.Id)
    FROM r_tab U
    LEFT JOIN Agent (NOLOCK) ON Agent.AgentID = U.AgentID
       AND Agent.AgentCode IS NOT NULL
    LEFT JOIN Driver (NOLOCK) ON Driver.DriverId = U.DriverId
       AND Driver.DriverCode IS NOT NULL
GROUP BY COALESCE(Agent.AgentCode,Driver.DriverCode), U.CtryCode, U.CtryName
ORDER BY U.AgentCode, U.CtryCode, U.CtryName`enter code here`