SQL用条件区分列

时间:2019-03-14 09:02:34

标签: mysql sql database select distinct

我正在处理一个查询,当列CarId不为空时,我需要计算不同的LocationId行,如果它的CarId或{ {1}},但我尝试过的查询会区分所有null,即使其为空

0

所需的输出:

CarId

电流输出

@LocId int

    Select Count(distinct a.CarId) from VehicleDetails a 
        inner join VehicleDocuments b on a.DocId=b.DocId
        left join VehicleShipmentDetails dpg on dpg.VehicleShipmentId= b.VehicleShipmentId
        where b.LogicalDelete=0 and a.LogicalDelete=0 
        and (dpg.LocationId= @LocId or dpg.LocationId= 0 or dpg.LocationId is null)



|  ID  |    CarId       |    LocationId   |  DateCreated  |
|------+----------------+-----------------+---------------|
|   1  |       1        |        5        |   02/03/2019  |
|   2  |       2        |      null       |   01/14/2019  |
|   3  |       2        |        0        |   02/03/2019  |
|   4  |       2        |        5        |   12/30/2018  |
|   5  |       4        |        3        |   01/10/2019  |
|   6  |       3        |        5        |   02/14/2019  |
|   7  |       2        |        5        |   03/13/2019  |

我得到| ID | CarId | LocationId | DateCreated | +------+----------------+-----------------+---------------+ | 1 | 1 | 5 | 02/03/2019 | | 2 | 2 | null | 01/14/2019 | | 3 | 2 | 0 | 02/03/2019 | | 4 | 2 | 5 | 03/13/2019 | | 5 | 4 | 3 | 01/10/2019 | | 6 | 3 | 5 | 02/14/2019 | 的计数,但我需要有| ID | CarId | LocationId | DateCreated | +------+----------------+-----------------+---------------+ | 1 | 1 | 5 | 02/03/2019 | | 2 | 2 | 5 | 01/14/2019 | | 3 | 4 | 3 | 01/10/2019 | | 4 | 3 | 5 | 02/14/2019 | 作为计数

编辑:我的目标是,如果4的值是6CarId,但要删除行LocationId,但在我的当前代码中,它将所有行区别开Null0等于null

的CarId

2 个答案:

答案 0 :(得分:0)

您可以查询类似的内容,将your_table替换为您的实际数据集。

SELECT ID, CardId, LocationId, DateCreated
FROM your_table as T
WHERE NOT EXISTS (SELECT *
                  FROM your_table as T1
                  WHERE T.ID > T1.ID AND T.CarID = T1.CarID)

答案 1 :(得分:0)

在SQL中,可以使用CASE语句来管理条件(就像其他编程语言中的“ if then else”一样)。在您的情况下,此功能可能会有所帮助,因为您需要处理两种不同的情况。