2011-08-23 157 views
1

我有以下查詢:SQL Server查詢問題(計數可能?)

SELECT A.shipment_id 
     ,B.box_id 
     ,A.shipment_status 
FROM shipments A 
join boxes B on A.shipment_id = B.shipment_id 
where A.shipment_status = 2 
Group by B.box_id, A.shipment_id, A.shipment_status 

返回的結果集,看起來像這樣:

shipment_idbox_idshipment_status
101,boxA,2
101,boxB,2
101,boxC,2
102,box101,2
102,box102,2
103,boxA1,2
103,boxA2,2

我想是這樣返回的東西代替(示出的每一批盒的總量):

shipment_id箱計數shipment_status
101,3個,2
102,2,2
103,2 2

我該如何實現這個目標?

謝謝!

回答

8
SELECT A.shipment_id 
     ,COUNT(*) AS boxcount 
     ,A.shipment_status 
FROM shipments A 
join boxes B on A.shipment_id = B.shipment_id 
where A.shipment_status = 2 
Group by A.shipment_id, A.shipment_status 

只是需要從GROUP BY刪除box_id,並使用COUNT,正如你在標題說。

0

試試這個:

SELECT A.shipment_id 
    , count(1) 
    , A.shipment_status 
    FROM shipments A 
    join boxes B on A.shipment_id = B.shipment_id 
where A.shipment_status = 2 
Group by A.shipment_id, A.shipment_status