我有如下表:彙總基於一個共同的列值從同一個表中唯一的一對列值的
my_table
------------------------
| common_id | uniq_val |
------------------------
| 1 | foo |
------------------------
| 1 | bar |
------------------------
我想總價值從它使得生成的查詢看起來像:
DESIRED RESULT
---------------------------------------
| common_id | uniq_val_1 | uniq_val_2 |
---------------------------------------
| 1 | foo | bar |
---------------------------------------
OR
---------------------------------------
| common_id | uniq_val_1 | uniq_val_2 |
---------------------------------------
| 1 | bar | foo |
---------------------------------------
所以我寫查詢:
SELECT t1.common_id, t1.uniq_val, t2.uniq_val
FROM my_table t1 JOIN my_table AS t2
ON t1.common_id=t2.common_id
WHERE t1.uniq_val!=t2.uniq_val;
導致
RESULTING SELECT
---------------------------------------
| common_id | uniq_val_1 | uniq_val_2 |
---------------------------------------
| 1 | foo | foo |
---------------------------------------
| 1 | bar | bar |
---------------------------------------
但我只需要這些列中的一個,所以我應該能夠做一個GROUP BY t1.common_id,如:
SELECT t1.common_id, t1.uniq_val, t2.uniq_val
FROM my_table t1 JOIN my_table AS t2
ON t1.common_id=t2.common_id
WHERE t1.uniq_val!=t2.uniq_val
GROUP BY t1.common_id;
不幸的是這將返回錯誤:
ERROR: column "t1.uniq_val" must appear in the GROUP BY clause or be used in an aggregate function
任何人都可以指出我的邏輯錯誤嗎?
將分別common_id值始終只有2個獨特的價值?有些人有2人,其他人有3人或4人? –