简体   繁体   English

PostgresQL 用聚合分组列

[英]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.其中asset 和asset_alt 值将合并为一列(asset),价格将根据资产从price 或price_alt 得出。

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?其中asset 和asset_alt 值将合并为一列(asset)asset_alt 和asset 之间的关系是什么?

If asset_alt is empty then use asset:如果asset_alt 为空,则使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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