Postgresql:计算具有相同值但顺序不同的行

时间:2014-02-02 20:43:09

标签: sql postgresql

我正在尝试计算此表中的行:

Product | Product2 | Value
Coke    | Lemon    |   3
Coke    | Potato   |   4
Coke    | Seven Up |   10
Lemon   | Coke     |   3
Lemon   | Meat     |   4
Pancake | Meat     |   23
Potato  | Coke     |   4
Seven Up| Coke     |   10
Meat    | Lemon    |   4
Meat    | Pancake  |   23

我必须计算物品,但如果他们改变了订单,我仍然必须算一次。 所以在这种情况下我会得到一个结果:5。 顺便说一句,我已经尝试过“Product!= Product2”,但这还不够。

有人可以告诉我在这种情况下该怎么办?谢谢,

2 个答案:

答案 0 :(得分:4)

由于您只有两列,因此可以使用greatest and least忽略列顺序:

select greatest(product, product2) as a,
       least(product, product2) as b
from t
order by a, b

会给你:

Lemon    | Coke
Lemon    | Coke
Meat     | Lemon
Meat     | Lemon
Pancake  | Meat
Pancake  | Meat
Potato   | Coke
Potato   | Coke
Seven Up | Coke
Seven Up | Coke

然后投放distinctcount

select count(
  distinct (
    greatest(product, product2),
    least(product, product2)
  )
)
from t

演示:http://sqlfiddle.com/#!15/32111/6

答案 1 :(得分:2)

基于This array sorting function,我们可以将行转换为数组,对数组进行排序,然后选择不同的值:

CREATE OR REPLACE FUNCTION array_sort (ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT unnest($1) ORDER BY 1)
$$;

而不是:

SELECT count( distinct array_sort(array[product, product2]  ) ) FROM your_table

希望有所帮助