向下舍入到最接近的 N 的倍数

Round down to nearest of Multiple of N

我有sqltable如下

+-----------------------------+
| |col1 |  col2 | col3| col4| |
+-----------------------------+
| _______________________     |
| | a | 3   | d1 | 10 |       |
| | a | 6   | d2 | 15 |       |
| | b | 2   | d2 | 8  |       |
| | b | 30  | d1 | 50 |       |
+-----------------------------+

我想把上面的table改成下面的,这里的转换是 col4 = col4 - (col4 % min(col2) group by col1)

+------------------------------+
| |col1 |  col2 | col3| col4|  |
+------------------------------+
| ____________________________ |
| |a | 3   | d1 | 9  |         |
| |a | 6   | d2 | 15 |         |
| |b | 2   | d2 | 8  |         |
| |b | 30  | d1 | 50 |         |
|                              |
+------------------------------+

我可以在应用程序代码中阅读上面的 table 以手动进行转换,想知道是否可以将转换卸载到 sql

您可以使用多 table UPDATE 来实现您想要的结果,将您的 table 加入 table 的 MIN(col2) 值:

UPDATE table1
SET col4 = col4 - (col4 % t2.col2min)
FROM (SELECT col1, MIN(col2) AS col2min
      FROM table1
      GROUP BY col1) t2 
WHERE table1.col1 = t2.col1

输出:

col1    col2    col3    col4
a       3       d1      9
a       6       d2      15
b       2       d2      8
b       30      d1      50

Demo on dbfiddle

只是 运行 一个简单的 select 查询:

select col1, col2, col3,
       col4 - (col4 % min(col2) over (partition by col1))
from t;

不需要实际修改table。