如何在SQL查询中将多个记录分组为一个

时间:2018-05-30 12:34:44

标签: sql sql-server

我需要运行一个查询来从我的SQL数据库中的两个视图中获取数据。 第一。 我从我的vw_BillsOfLading获取所需的列,然后我使用左外连接从我的项目视图中获取件和重量,其中我的项目的事务ID =提单ID。

这是我遇到挑战的地方。

在大多数情况下,我在每张提单上都有多个项目记录。好吧,我想为我的提单显示一条记录,并获得每张提单记录的重量和件数之和。

请帮助我,谢谢你。

这是我的查询

SELECT
                b.BillOfLadingNumber
              , b.ShipFromCity
              , b.ShipFromState
              , b.ShipFromZip
              , b.DeliveryDate
              , b.ShipToCity
              , b.ShipToState
              , b.ShipToZip
              , i.Weight
              , i.Pieces
              , b.Id
              , i.TransactionId
FROM
                vw_BillsOfLading b
                Left Outer join
                                vw_Items i
                                on
                                                i.TransactionId = b.Id
WHERE
                BillOfLadingNumber in ('100277' ,'100310' ,'100814' ,'100867' ,'101118' ,'101124' ,'101530' ,'101630' ,'101657' ,'101694' ,'101760' ,'102153' ,'102241' ,'102276' ,'102284')
GROUP BY
                b.BillOfLadingNumber
              , b.ShipFromCity
              , b.ShipFromState
              , b.ShipFromZip
              , b.DeliveryDate
              , b.ShipToCity
              , b.ShipToState
              , b.ShipToZip
              , i.Weight
              , i.Pieces
              , b.Id
              , i.TransactionId

enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个(在这里从臀部拍摄 - 我在这台机器上没有SQL Server实例):

{{1}}

答案 1 :(得分:0)

只需从您的分组中删除i.weighti.pieces

select b.billofladingnumber, b.shipfromcity, b.shipfromstate, b.shipfromzip, b.deliverydate, b.shiptocity, b.shiptostate, b.shiptozip, , b.id, i.transactionid, sum(i.weight) weight, sum(i.pieces) pieces
from vw_billsoflading b left outer join vw_items i on i.transactionid = b.id
where billofladingnumber in ('100277','100310','100814','100867','101118','101124','101530','101630','101657','101694','101760','102153','102241','102276','102284') 
group by b.billofladingnumber, b.shipfromcity, b.shipfromstate, b.shipfromzip, b.deliverydate, b.shiptocity, b.shiptostate, b.shiptozip, , b.id, i.transactionid

答案 2 :(得分:0)

Sum是你的朋友:

SELECT
    b.BillOfLadingNumber
  , b.ShipFromCity
  , b.ShipFromState
  , b.ShipFromZip
  , b.DeliveryDate
  , b.ShipToCity
  , b.ShipToState
  , b.ShipToZip
  , i.Weight
  , i.Pieces
  , b.Id
  , i.TransactionId
FROM
    vw_BillsOfLading b
    Left Outer join
        vw_Items i
        on
            i.TransactionId = b.Id
WHERE
    BillOfLadingNumber in ('100277' ,'100310' ,'100814' ,'100867' ,'101118' ,'101124' ,'101530' ,'101630' ,'101657' ,'101694' ,'101760' ,'102153' ,'102241' ,'102276' ,'102284')
GROUP BY
    b.BillOfLadingNumber
  , b.ShipFromCity
  , b.ShipFromState
  , b.ShipFromZip
  , b.DeliveryDate
  , b.ShipToCity
  , b.ShipToState
  , b.ShipToZip
  , i.Weight
  , i.Pieces
  , b.Id
  , i.TransactionId