我想用SUM
从SQL中的不同表中收集数据。我想将产品的piece
和price
相乘并在其旁边添加cargoprice
,但我必须使用其中之一,因为cargoprice
位于多行上。但我不能使用DISTINCT
如下:
SELECT
SUM((tbl_Product.price * piece) + DISTINCT(tbl_Cargo.cargoprice)) AS total
FROM tbl_Order
LEFT JOIN tbl_Product ON tbl_Product.productid = tbl_Order.productid
LEFT JOIN tbl_Cargo on tbl_Cargo.cargoid = tbl_Order.cargoid
WHERE userid = '1'
答案 0 :(得分:0)
您可以使用" group by"在您的查询中。示例代码如下;
select SUM(price*piece)+cargoPrice,cargoPrice from (
select 5 as price,2 as piece,1 as cargoPrice
union all
select 5 as price,2 as piece,1 as cargoPrice
union all
select 5 as price,2 as piece,2 as cargoPrice
union all
select 5 as price,3 as piece,2 as cargoPrice
union all
select 5 as price,4 as piece,3 as cargoPrice
)A
group by cargoPrice
答案 1 :(得分:0)
一个货物可以包含多个订单。因此,您可能会将#1和#2订单与#100货物一起发货,订单#3和#4随货物#200一起发货。所以你需要两个订单的总和,但在这个例子中只需要两个货物。
要解决此问题,请按货物分组您的订单:
select sum(per_cargo.pricesum + tbl_cargo.cargoprice) as total
from
(
select o.cargoid, sum(p.price * p.piece) as pricesum
from tbl_order o
join tbl_product p on p.productid = o.productid
where o.userid = 1
group by o.cargoid
) per_cargo
join tbl_cargo on tbl_cargo.cargoid = per_cargo.cargoid ;
答案 2 :(得分:-1)
我用这段代码解决了问题:SELECT DISTINCT(tbl_Cargo.cargoprice) + SUM(tbl_Product.price * piece) AS total
FROM tbl_Order
LEFT JOIN tbl_Product ON tbl_Product.productid = tbl_Order.productid
LEFT JOIN tbl_Cargo on tbl_Cargo.cargoid = tbl_Order.cargoid
WHERE userid = '1' GROUP BY tbl_Cargo.cargoprice