我试图通过选择2列的不同组合来获取行(“column_a”和“column_b”,如下例所示),并在MySQL中使用一个sql查询获取每个区别的结果的最新日期时间行。最好是看样本数据而不是阅读我的英语。
sample_table(简化了“created_datetime”列)
SELECT SUM(a) as total_a, SUM(b) as total_b, (sum(a) + sum(b)) as grand_total
FROM table
我理想的结果
id column_a column_b column_c created_datetime
-----------------------------------------
1 100 200 aaaa t
2 200 100 bbbb t+20
3 100 300 cccc t+40
4 100 200 zzzzzzz t+60
以下是我尝试的一些模式:
A:
id column_a column_b column_c created_datetime
-----------------------------------------
3 100 300 cccc t+40
4 100 200 zzzzzzz t+60
结果将是
SELECT DISTINCT
column_a,
column_b,
MAX(created_datetime)
FROM sample_table
GROUP BY column_a, column_b;
B:
100 200 t+60
100 300 t+40
200 100 t+20
结果将是
SELECT DISTINCT
least(column_a, column_b) as column_a,
greatest(column_a, column_b) as column_b
FROM sample_table
GROUP BY column_a, column_b;
C:
100 200
100 300
结果将是
SELECT DISTINCT
least(column_a, column_b) as column_a,
greatest(column_a, column_b) as column_b,
MAX(created_datetime)
FROM sample_table
GROUP BY column_a, column_b;
我试图在没有任何其他语言(如JavaScript或Python)的结果获得数据后进行调整。是不可能用一个SQL查询来实现这一点,还是我需要采取进一步的MySQL步骤?提前谢谢。
答案 0 :(得分:0)
SELECT sample_table.column_a,
sample_table.column_b,
sample_table.column_c,
sample_table.created_datetime
FROM sample_table
INNER JOIN (SELECT least(column_a, column_b) as column_a,
greatest(column_a, column_b) as column_b,
MAX(created_datetime) as created_datetime
FROM sample_table
GROUP BY least(column_a, column_b),
greatest(column_a, column_b)) t
ON t.column_a = least(sample_table.column_a, sample_table.column_b)
AND t.column_b = greatest(sample_table.column_a, sample_table.column_b)
AND t.created_datetime = sample_table.created_datetime