我有这些表:我需要使用相同的KEY1&和“SUM”所有VALUES。 KEY3当KEY3 = X
时| KEY1 | VALUE1 | KEY2 | VALUE2 | KEY3 |
| 1 | 9 | 2 | 2 | x |
| 1 | 10 | 2 | 3 | x |
| 2 | 5 | 1 | 8 | x |
| 2 | 5 | 1 | 9 | y |
将key1选为k1,将key2选为k2 FROM table1 WHERE key3 = x
对于这些查询的每个结果,我需要这样做:
SELECT
COALESCE(SUM(case when key1 = k1 then totalamount1 else 0 end),0) +
COALESCE(SUM(case when key2 = k2 then totalamount2 else 0 end),0) as total
FROM table1
WHERE key3 = x
Y需要这些输出:
Total
id 1: 27
id 2: 10
我如何加入两个查询?
谢谢!
答案 0 :(得分:0)
最简单的方法是“取消”你的桌子:
SELECT
Key,
SUM(Value) AS Total
FROM (
SELECT Key3, Key1 AS Key, Value1 AS Value FROM Table1
UNION ALL SELECT Key3, Key2, Value2 FROM Table1
) NormTable
WHERE Key3 = 'x'
GROUP BY Key
您还可以将WHERE Key3 = 'x'
移动到联合查询的每个中。这会更快,但更容易出错,因为如果您需要不同的Key3
值,则需要在每个查询中更改它。你打电话给那个。
答案 1 :(得分:0)
以下是获得结果的一种方法:
SELECT IF(i.i,t.key1,t.key2) AS `id`
, SUM(IF(i.i,t.value1,t.value2)) AS `Total`
FROM table1 t
CROSS
JOIN (SELECT 0 AS i UNION ALL SELECT 1) i
WHERE t.key3 = 'x'
GROUP
BY IF(i.i,t.key1,t.key2)
SQL Fiddle demo here: http://sqlfiddle.com/#!2/d7599f/1
我使用的“技巧”是通过执行table1与包含两行的集合的交叉连接来获取两组行;这两行可以通过条件测试相互区分。
由于i.i
的值将为1
或0
,这意味着它将在IF函数中作为条件测试评估为TRUE和FALSE。
我们可以从一组行中提取(key1,value1),并从另一组中提取(key2,value2),基本上,创建一个这样的结果集:
| i | keyN | valueN |
| 1 | 1 | 9 |
| 1 | 1 | 10 |
| 1 | 2 | 5 |
| 0 | 2 | 2 |
| 0 | 2 | 3 |
| 0 | 1 | 8 |
现在,这只是做SUM(valueN) GROUP BY keyN
上面的查询可以用(更可移植的)SQL-92样式重写:
SELECT CASE WHEN i.i = 1 THEN t.key1 ELSE t.key2 END AS `id`
, SUM(CASE WHEN i.i = 1 THEN t.value1 ELSE t.value2) AS `Total`
FROM table1 t
CROSS
JOIN (SELECT 0 AS i UNION ALL SELECT 1) i
WHERE t.key3 = 'x'
GROUP
BY CASE WHEN i.i = 1 THEN t.key1 ELSE t.key2 END AS `id`
(对于Oracle,我们需要在内联视图中的每个选择中添加FROM DUAL
别名为i。)