SQL 多列选择 - 获取过期数据和空列

问题描述 投票:0回答:1

我有一个包含 3 列的表:id、expire、lastwdIf

如何进行查询,以便对于每个唯一的 id,我在同一行中只有 12 月份的“到期”列,并在同一行中找到 lastwdIf(只有一个寄存器为 null每个 id) 列的值为 null?


| id       | expire   || last wdIf|| Name     | Vendor   |
| -------- | -------- || -------- || -------- | -------- |
| 10       | 10/01    || d23dv36  || Juan     | 25,5     |
| 15       | 12/04    || 2232cg   || Maria    | 36,4     | 
| 15       |          || null     || Maria    |  14,1    | 
| 10       | 12/17    || 2232cg   || Juan     | 10,2     | 
| 10       |          || null     || Juan     |  32,10   |



结果必须是:

| id       | expire   || last wdIf|| Name     | Vendor   |
| -------- | -------- || -------- || -------- | -------- |
| 10       | 12/17    || null     || Juan     | 32,10    |
| 15       | 12/04    || null     || Maria    | 14,1     | 

我尝试过一些 SELECT 案例加入,但没有任何效果:(

mysql join merge count
1个回答
0
投票

您可以通过自加入来完成此操作。将表与其自身连接,匹配 id 上的行,但仅匹配

expire
为空的行。

select t1.id, t1.expire, t2.lastwdif, t2.name, t2.vendor
from test t1
join test t2 
  on t1.id = t2.id and t2.expire is null
where left(t1.expire, 3) = '12/'
order by id;

示范.

© www.soinside.com 2019 - 2024. All rights reserved.