我如何计算一行拥有多少个不同的值?

时间:2017-03-08 07:47:26

标签: mysql sql sqlite

假设我给出了纸质路线数据库。

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次,我只想知道他有多少条路线。

我认为我需要使用集合论或外部联接,但到目前为止我无法解决这个问题。

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分: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;