简体   繁体   中英

PostgresQL grouping columns with aggregate

I currently have a table with the following columns:

asset, asset_alt, price, price_alt, time

Trying to view the combined values to ideally return something like this:

asset, price, time

Wherein the asset and asset_alt values would be combined into one column (asset) and the price would be derived from either price or price_alt depending on the asset.

I have tried something like this, but it doesn't provide proper averages for the assets and also doesn't follow the ideal return format mentioned above.

SELECT
ab.asset,
ab.asset_alt,
time_bucket('01:00:00'::interval, ab."time") AS bucket,
avg(ab.price) AS price,
avg(ab.price_alt) AS price_alt,
FROM assets ab
GROUP BY ab.asset, ab.asset_alt, (time_bucket('01:00:00'::interval, ab."time"));

Wherein the asset and asset_alt values would be combined into one column (asset) What is a relation between asset_alt and asset?

If asset_alt is empty then use asset:

select 
COALESCE(ab.asset_alt, ab.asset) AS asset, -- join assets columns in one
-- use right price column
CASE 
  WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
  ELSE ab.price
END AS price
 FROM FROM assets ab
GROUP BY 
  COALESCE(ab.asset_alt, ab.asset),
  CASE 
   WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
   ELSE ab.price
  END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM