【问题标题】:Need assistance with T-SQL query UNION, JOINS, COUNT在 T-SQL 查询 UNION、JOINS、COUNT 方面需要帮助
【发布时间】:2016-12-12 05:06:02
【问题描述】:

看起来我很难通过查询来汇总按联合运营商分组的货物。今天我正在检索由代理、司机 (U.AgentCode) 运送到特定国家 (U.CtryCode、U.CtryName) 的总出货量 (count(Distinct. U.SjipmentId)。我最不想做的事情是将所有出货量相加得到出货总量。 有人会建议我如何以简单易行的方式实现这一目标吗? 您可以在下面找到我最新的查询。

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

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

Union 语句需要具有完全相同的列名,在您的 Union All 命令下方的代码中,试试这个:

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

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

【讨论】:

    【解决方案2】:

    您的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`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多