我有一个名为production_cost
的表。
product | per_day_product_cost
------------+-------------------------
powder | 40
而且,我还有一个名为daily_production
的表。
date | product | type
------------+------------+----------
2018-09-09 | powder | talcum
2018-09-09 | powder | chilli
我需要从product
列上联接的两个表中获取结果。
由于每天的总费用为40
,因此我需要将值划分为两种产品类型,结果是
date | product | type | cost
------------+------------+----------+--------
2018-09-09 | powder | talcum | 20
2018-09-09 | powder | chilli | 20
我在使用count时尝试了案例,但我耗尽了所有想法来达到最终结果。 我是后端查询的新手,所以如果还有其他方法可以做到,也请让我知道。
答案 0 :(得分:1)
您可以尝试使用COUNT
窗口函数从product
表中按daily_production
获取总数。然后编写一个子查询,以从product
获得每个production_cost
的总费用。
CREATE TABLE production_cost(
product VARCHAR(50),
per_day_product_cost INT
);
INSERT INTO production_cost VALUES ('powder' ,40);
CREATE TABLE daily_production(
date TIMESTAMP, product VARCHAR(50), type VARCHAR(50)
);
INSERT INTO daily_production VALUES ('2018-09-09', 'powder','talcum');
INSERT INTO daily_production VALUES ('2018-09-09', 'powder','chilli');
查询1 :
SELECT *,(
select SUM(per_day_product_cost)
from production_cost pc
WHERE pc.product = dp.product
GROUP BY pc.product) /COUNT(*) OVER(PARTITION BY product ORDER BY product) as cost
FROM daily_production dp
Results :
| date | product | type | cost |
|----------------------|---------|--------|------|
| 2018-09-09T00:00:00Z | powder | talcum | 20 |
| 2018-09-09T00:00:00Z | powder | chilli | 20 |
答案 1 :(得分:0)
使用联接和子查询
select t1.*,t2.cost from
(
select p.* from production_cost c
join daily_production p
on c.product=p.product
) as t1 join
(
select p.product, c.per_day_product_cost/count(p.product) as cost
from production_cost c
join
daily_production p
on c.product=p.product
group by p.product,c.per_day_product_cost
) as t2
on t1.product=t2.product
date product type cost
09/09/2018 00:00:00 powder talcum 20
09/09/2018 00:00:00 powder chilli 20
答案 2 :(得分:0)
尝试在以下子查询中对产品类型计数进行计数,然后使用count来划分产品总成本
select d.date,d.product,d.type,(p.per_day_product_cost/c) as cost
from product p
inner join
(select product,count(type) as c from daily_production
group by product)a on p.product=a.product
inner join daily_production d on p.product=d.product
答案 3 :(得分:0)
select
d.date,
d.product,
d.type,
p.per_day_product_cost/(select count(1)
from daily_production d1
where d1.product=d.product and d1.date=d.date) cost
from daily_production d,production_cost p
where d.product=p.product;
答案 4 :(得分:0)
免责声明:仅当所有单一产品的费用始终完全相同时,此方法才有效。如果一种成分可能是成本为100的黄金,而另一种成分是10的木材,则此方法不再起作用。我假设每种产品的成分数量可以作为整个产品成本的分配器。
使用窗口功能COUNT
(https://www.postgresql.org/docs/current/static/tutorial-window.html):
SELECT
dp.*,
pc.per_day_product_cost /
count(*) OVER (PARTITION by pc.product, dp.prod_date) as cost
FROM
daily_production dp
JOIN production_cost pc
ON dp.product = pc.product
COUNT
窗口函数将行分组。在您的情况下,将为每个日期和产品创建一个组。然后,它计算这些组中的所有行。此结果将作为per_day_production_cost
的分隔符,并设置为每一行的新列。
请注意,“日期”是Postgres中的保留字。最好重命名您的列。我将其重命名为“ prod_date”。