postgresql - Postgresql SUM 计算列
问题描述
我正在尝试创建一些 sql 来计算用户库存的价值,并设法让它工作到最后一步。
SELECT DISTINCT ON (pricing_cards.card_id)
(inventory_cards.nonfoil * pricing_cards.nonfoil) + (inventory_cards.foil * pricing_cards.foil) as x
FROM inventory_cards
INNER JOIN pricing_cards ON pricing_cards.card_id = inventory_cards.card_id
WHERE inventory_cards.user_id = 1
ORDER BY pricing_cards.card_id, pricing_cards.date DESC;
上面的代码带回了一个具有正确计算卡的列。我现在需要将这一列相加,但是当我尝试对其求和时不断出错。
添加SUM((inventory_cards.nonfoil * pricing_cards.nonfoil) + (inventory_cards.foil * pricing_cards.foil))
会引发以下错误
ERROR: column "pricing_cards.card_id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 6: ORDER BY pricing_cards.card_id, pricing_cards.date DESC;
添加GROUP BY pricing_cards.card_id, pricing_cards.date
似乎可以修复错误,但会返回同一列计算值。
所以:
SELECT DISTINCT ON (pricing_cards.card_id)
SUM((inventory_cards.nonfoil * pricing_cards.nonfoil) + (inventory_cards.foil * pricing_cards.foil)) as x
FROM inventory_cards
INNER JOIN pricing_cards ON pricing_cards.card_id = inventory_cards.card_id
WHERE inventory_cards.user_id = 1
GROUP BY pricing_cards.card_id, pricing_cards.date
ORDER BY pricing_cards.card_id, pricing_cards.date DESC;
回报:
X |
---|
0.71 |
29.92 |
25.67 |
171.20 |
0.32 |
0.26 |
解决方案
我建议您使用子查询来获取最新的定价数据,然后加入并求和:
SELECT
SUM(inventory_cards.nonfoil * latest_pricing.nonfoil + inventory_cards.foil * latest_pricing.foil)
FROM inventory_cards
INNER JOIN (
SELECT DISTINCT ON (card_id)
card_id, nonfoil, foild
FROM pricing_cards
ORDER BY pricing_cards.card_id, pricing_cards.date DESC
) AS latest_pricing USING (card_id)
WHERE inventory_cards.user_id = 1
有关子查询中的备选方案,另请参阅选择每个 GROUP BY 组中的第一行?并优化 GROUP BY 查询以检索每个用户的最新行。
推荐阅读
- ruby-on-rails - Rails - 从集合中获取多态子项作为 ActiveRecord::Relation
- r - 带有网格的地图中的线交叉(ggplot)
- android - android更快的截屏方式?
- java - java中是否有真正的异步文件访问器?
- asp.net - VB.NET WSP 到 WAP 的转换
- npm - bootstrap-sass 无法在 amazon linux 实例上正确安装
- sql - 在 T-SQL 中插入表变量,其值包含反斜杠
- c# - Selecting unique values of different columns using LINQ
- android - 片段按钮导致回栈错误
- angular - 打字稿模块导入问题