我在MySQL中制定查询时遇到了一些问题。
这就是我在数据库中的内容
Part # Desc. Tracking # EquivalentKey Qty PriceEach
A aa 123 1 2 .30
B dd 342 1 10 1.40
C dfd 2343 2 100 3
D awe 43455 3 90 6
E dffd 5643 2 10 5
所以给定这些数据,这是我想要的输出
Part# Equivalent Part # 1 Total Qty Weighted Avg Price
A B 12 1.358
......等等
Basiclly我想通过PN分组,然后通过Equivalent PN分组,并显示同一行中的所有PN,添加tot 知道怎么做吗?我确实尝试了Group By功能但它给了我另一行等效PN
非常感谢您提前
答案 0 :(得分:1)
你可以做的是:
SELECT
GROUP_CONCAT(Part) AS Parts
, EquivalentKey
, SUM(Qty) AS Total_Qty
, SUM(Qty * PriceEach) / SUM(Qty)
AS Weighted_Avg_Price
FROM
table
GROUP BY
EquivalentKey ;
答案 1 :(得分:1)
如果您没有GROUP_CONCAT()
,那么您可以使用以下内容,假设每个EquivalentKey只有两个部分:
select min(partno) PartNo,
max(partno) EquivalentPartNo,
TotalQty,
WeighedAvgPrice
from yourtable t1
left join
(
select EquivalentKey,
sum(qty) TotalQty,
sum(qty * priceeach) / sum(qty) WeighedAvgPrice
from yourtable
group by EquivalentKey
) src
on t1.EquivalentKey = src.EquivalentKey
group by TotalQty, WeighedAvgPrice;
或没有子查询:
select min(partno) PartNo,
max(partno) EquivalentPartNo,
sum(qty) TotalQty,
sum(qty * priceeach) / sum(qty) WeighedAvgPrice
from yourtable t1
group by EquivalentKey;
如果您有权访问GROUP_CONCAT()
,那么您将使用:
select GROUP_CONCAT(partno) PartNo,
sum(qty) TotalQty,
sum(qty * priceeach) / sum(qty) WeighedAvgPrice
from yourtable t1
group by EquivalentKey;