计数/组BY

时间:2015-02-03 10:59:47

标签: sql-server-2008 count group-by

我有以下查询:

SELECT
        CONVERT(varchar(20),GetDate(),103) as 'Today''s Date'
        ,(D.Forename + ' ' + D.Surname) as 'Driver Name'
        ,V.Registration as 'Allocated Truck Reg'
        ,R.CollectionCompanyTown as 'Collection Location'
        ,R.DeliveryCompanyTown as 'Delivery Location'
        ,R.[Collection Date]
        ,R.[Delivery Date]
        ,R.[Fee Charge] as 'Revenue'
        ,R.Quantity
        ,R.ReservationsID
        ,C.[Trading Name] as 'Customer'
        ,Count([Customers Order Ref]) as count
        ,R.[Customers Order Ref]

FROM
        tblReservation R
        --LEFT JOIN tblDeliveryStages ds ON ds.ReservationsID = R.ReservationsID
        LEFT JOIN tblDriver D ON D.DriverID = R.DriverID
        LEFT JOIN tblVehicle V ON V.VehicleID = R.VehicleID
        LEFT JOIN tblCustomer C ON C.CustomerID = R.CustomerID
        LEFT JOIN tblReservationItems RI on RI.ReservationsID = r.ReservationsID and RI.Deleted != 1
        LEFT JOIN tblManifestReservation MR ON MR.ReservationsID = R.ReservationsID
        LEFT JOIN tblLoadManifest LM ON LM.LoadManifestID = MR .LoadManifestID




GROUP BY
        R.[Customers Order Ref]
        ,R.ReservationsID
        ,D.Forename 
        ,D.Surname
        ,V.Registration
        ,R.CollectionCompanyTown 
        ,R.DeliveryCompanyTown
        ,R.[Collection Date]
        ,R.[Delivery Date]
        ,R.[Fee Charge] 
        ,R.Quantity
        ,R.[Customers Order Ref]
        ,C.[Trading Name]


ORDER BY ReservationsID desc

两个主要部分是reservationsID和Customers Order Ref。 ReservationsID将始终是唯一的,客户订单参考不会,有些预订将共享相同的客户订单参考。

我想知道有多少预订分享客户订单参考,但当前的计数字段只返回以下内容:

Data returned

1 个答案:

答案 0 :(得分:2)

您可以使用COUNT()的{​​{3}}并完全删除GROUP BY子句。类似的东西:

Count(*) OVER (PARTITION BY [Customers Order Ref])

如果我已经理解了您正确要求的内容。