我有一个包含4列的MySQL表,我们将其称为C1,C2,C3和C4。
在此数据中,我有一个像这样的数据集:
C1,C2,C3,C4
A,B,12,24
C,D,23,13
A,D,19,15
B,C,15,15
A,C,21,9
B,D,19,2
B,A,8,19
D,C,29,1
我需要获得如下输出:
A,71
B,66
D,59
C,48
我试图写一个查询,但是当其他两个字段相等并对其进行分组/排序时,似乎似乎无法将两个字段求和。
SELECT C1, SUM(C3,C4) AS Total
WHERE C1 = C2
GROUP BY C1
ORDER BY C1 Desc;
这将返回一个空集,我知道为什么,如果C1和C2在同一行中不相等,但似乎无法弄清楚下一步该怎么做。
答案 0 :(得分:2)
第一个解决方案(MySql 8.0):
{$toDate: {
$add: [{
"$subtract": [
dts,
new Date("1970-01-01T00:00:00Z")
]},
1000*60*60*24,
]
}}
请参见demo
第二个解决方案(MySql 5.7):
WITH d AS (
SELECT DISTINCT C1 AS name FROM tablename
UNION
SELECT DISTINCT C2 AS name FROM tablename
)
SELECT tt.name, SUM(tt.value) AS total FROM (
SELECT
d.name,
CASE WHEN t.C1 = d.name THEN C3 ELSE 0 END + CASE WHEN t.C2 = d.name THEN C4 ELSE 0 END AS value
FROM d
INNER JOIN tablename AS t
ON t.C1 = d.name OR t.C2 = d.name
) AS tt
GROUP BY name;
请参见demo
答案 1 :(得分:1)
我会这样:
select col, sum(val)
from ((select c1 as col, c3 as val from t
) union all
(select c2, c4 from t
)
) cc
group by col;
根据您提供的数据,这似乎是最简单的方法。这比在or
条件下使用join
的方法具有更好的性能。