寻找道路的总成本

时间:2015-09-28 20:49:46

标签: mysql

我有一个包含3列REF Handle Size Price 2002 t-shirt1 M 23 2003 t-shirt1 L 23 3001 t-shirt2 S 24 3002 t-shirt2 M 24 3003 t-shirt2 L 24 sourcedest的表格,其值为

total cost

我想要总成本

Agra Delhi 500
Agra Kanpur 400
Delhi Agra 900
Kanpur Agra 500

2 个答案:

答案 0 :(得分:4)

您可以使用LEAST()和GREATEST()函数以及GROUP BY查询:

SELECT
  LEAST(source, dest),
  GREATEST(source, dest),
  SUM(total_cost)
FROM
  tablename
GROUP BY
  LEAST(source, dest),
  GREATEST(source, dest)

答案 1 :(得分:2)

SELECT a.source, a.dest, (a.total_cost + b.total_cost) round_trip_cost
FROM my_tab as a 
    LEFT OUTER JOIN my_tab as b 
    ON (a.source = b.dest AND b.source = a.dest)