0

我有这些表:当 KEY3 = X 时,我需要使用相同的 KEY1 和 KEY2 “汇总”所有值

| 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  |

SELECT key1 as k1, key2 as 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 

我怎样才能加入这两个查询?

谢谢!

4

2 回答 2

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值,则需要在每个查询中更改它。你打电话给那个。

于 2013-07-31T18:41:46.580 回答
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 演示在这里:http://sqlfiddle.com/#!2/d7599f/1


我使用的“技巧”是通过执行 table1 与恰好包含两行的集合的交叉连接来获得两组行;这两行可以通过条件测试相互区分。

由于 的值为i.i10这意味着它将评估为 TRUE 和 FALSE 作为 IF 函数中的条件测试。

我们可以从一组行中提取 (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 的内联视图中添加每个选择。)


于 2013-07-31T18:53:00.813 回答