我在创建sql查询时遇到问题。我有这样的情况
ColumnA ColumnB ColumnC1 4 text123
1 5
1 6
1 7如何进行查询,使其使用第1/4行的值自动填充C列?
我想: if columnA Value=1和ColumnB Value=5和ColumnC Value=NULL than取ColumnC行的值,其中A=1和B=4,然后用如下方式填充ColumnC值
Column A Column B Column C1 4 text123
1 5 text123
1 6
1 7对于columnA =2 columnA = 3这样的其他条目,我也需要使用它。
发布于 2017-11-28 00:49:14
使用用户变量和case语句很容易做到:
注意:此逻辑模拟其他RDBM系统中的滞后/超前分析/窗口功能。MySQL目前不支持窗口/分析函数。
SELECT ColumnA
, ColumnB
, case when columnC is null then @PriorVal
else @PriorVal:=ColumnC end as ColumnC
FROM YourTableName
CROSS JOIN (SELECT @PriorVal:='') z
ORDER BY ColumnA, ColumnB;我们使用uservariable @PriorVal来跟踪不为空的C值,然后根据顺序columnA,ColumnB用该值替换C中的空值。每次PriorValue具有非空值时,userVariable @PriorValue都会设置为C,并显示该值。只要columnC为空值,就会显示存储的PriorVal userVariable。这种方法在很大程度上依赖于order by。
@PriorVal是在上面的交叉连接派生表(z)中初始化的,这个方法使得它更容易与PHP结合使用,因为不需要传递两个单独的语句。
使用我的样本数据集:
Insert into foo_47514588 values
(1,4,'text123')
,(1,5,NULL)
,(1,6,NULL)
,(1,7,NULL)
,(1,8,'text2')
,(1,10,NULL)
,(2,1,'Text3');它实现了以下功能:
+----+---------+---------+---------+
| | ColumnA | ColumnB | COlumnC |
+----+---------+---------+---------+
| 1 | 1 | 4 | text123 |
| 2 | 1 | 5 | text123 | <--Added by case statement
| 3 | 1 | 6 | text123 | <--Added by case statement
| 4 | 1 | 7 | text123 | <--Added by case statement
| 5 | 1 | 8 | text2 |
| 6 | 1 | 10 | text2 | <--Added by case statement
| 7 | 2 | 1 | Text3 |
+----+---------+---------+---------+https://stackoverflow.com/questions/47514588
复制相似问题