2017-03-08 81 views
1

假設我有一個紙質路線數據庫。如何計算一行有多少個不同的值?

Create table routes(route_number varchar(100), route_length varchar(1000) 
Create table deliverers(deliv_name varchar(100)) 
Create table deliveries(Deliv_name varchar(100), route_number varchar(100), 
         number_of_papers varchar(100), date_of delivery date(yyyy-mm-dd)) 

(我知道這是不完整的,但我們不需要知道這個例子的鍵)

我想知道,每一個拯救者擁有,交付量不大路線的數量已經發生在每條路線上。如果送貨員A有3條路線,並且他每年運送100次這條路線,我只想知道他有多少條路線。

我想我需要使用集合論或外部連接,但即時無法解決這個問題。

+0

添加適當的數據樣本和預期的結果.. – scaisEdge

回答

0

試試這個:

SELECT deliverers.deliv_name As DeliveryPerson, COUNT(DISTINCT route_number) As RoutesCount 
FROM deliverers 
INNER JOIN deliveries ON deliveries.Deliv_name = deliverers.deliv_name 
GROUP BY (deliverers.deliv_name) 
0

使用此:

SELECT  A.deliv_name, COUNT(DISTINCT route_number) AS "NoOfRoutes" 
FROM  dbo.deliverers A 
      LEFT OUTER JOIN dbo.deliveries B 
       ON A.deliv_name = B.Deliv_name 
GROUP BY A.deliv_name 
0

集合函數可以使用DISTINCT聚集唯一不同的值:

SELECT deliv_name, 
     count(DISTINCT route_number) AS routes 
FROM deliveries 
GROUP BY deliv_name; 

但是,如果你想包括遞送員說還沒有很多交易,你也必須查看deliverers表。這是可以做到既具有outer join

SELECT deliv_name, 
     count(DISTINCT route_number) 
FROM  deliverers 
LEFT JOIN deliveries USING (deliv_name) 
GROUP BY deliv_name; 

correlated subquery

SELECT deliv_name, 
     (SELECT count(DISTINCT route_number) 
     FROM deliveries 
     WHERE deliv_name = deliverers.deliv_name 
     ) AS routes 
FROM deliverers; 
相關問題