如何从COALESCE分组? SQL

时间:2014-03-12 08:46:27

标签: sql

SELECT
    VehicleOwner,
    COALESCE(CarMileage, MotorcycleMileage, BicycleMileage, 0) AS Mileage,
    Count(*)
FROM
    VehicleMileage
Group by VehicleOwner
Having Count(*)>1

3 个答案:

答案 0 :(得分:0)

这很有效。

SELECT
    VehicleOwner,
    COALESCE(CarMileage, MotorcycleMileage, BicycleMileage, 0) AS Mileage,
    Count(*)
FROM
    VehicleMileage
Group by VehicleOwner, COALESCE(CarMileage, MotorcycleMileage, BicycleMileage, 0)
Having Count(*)>1

您还可以将COALESCE中的每一列放在GROUP BY部分中。取决于你想要实现的目标

答案 1 :(得分:0)

SELECT 
    VehicleOwner,
    SUM(COALESCE(CarMileage, 0)+COALESCE(MotorcycleMileage, 0)+COALESCE(BicicleMileage, 0)) AS Mileage,
    COUNT(*) cnt
FROM VehicleMileage
GROUP BY VehicleOwner
HAVING cnt > 1

答案 2 :(得分:0)

我明白了......

SELECT b.VehicleOwner, City
FROM (SELECT a.VehicleOwner,
      COALESCE(a.City, (Select b.City from a INNER Place b), 
              (Select b.City from a INNER   Place b)) AS City
      FROM VehicleMileage a) AS b
WHERE b.VehicleOwner IN (SELECT VehicleOwner 
                     FROM VehicleMileage 
                     GROUP BY VehicleOwner
                     HAVING COUNT(*)>1);