2010-03-16 70 views
0

这一语句将产生一个4列的表的总和:我如何获得第四列的

SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate, 
     'Delivery' AS Legend, -price*quantity AS amount 
    FROM product JOIN shipped ON (product.id = shipped.product) 
UNION 
    SELECT receipt.badguy, receipt.rdate,notes, amount 
    FROM receipt 

如何获得上述产生什么样的列第4的总和?

+0

哪个数据库? – 2010-03-16 21:48:25

+0

您的查询似乎不完整。 – 2010-03-16 21:49:30

回答

1

我喜欢使用子查询的一切。

SELECT SUM(results.amount) 
FROM 
(
SELECT -price*quantity AS amount 
    FROM product JOIN shipped ON (product.id = shipped.product) 
UNION 
    SELECT amount 
    FROM 
... 
) results 
+0

sql:error每个派生表都必须有自己的别名 number:1248 – 2010-03-16 21:47:48

+0

哦,是的,你需要一个子查询的别名。我会添加它。 – 2010-03-16 21:56:01

+0

在Oracle中,子查询表达式不需要别名。 'select count(dummy)from(select * from dual);'是完全有效的。 – 2010-03-16 22:22:53

1
SUM(-price*quantity) 

呵呵?

1

尝试

sum(price*quantity) 

或两个查询合并为

SELECT badguy,rdate,notes,SUM(AMOUNT) FROM(
     SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate, 
     'Delivery' AS Legend, -price*quantity AS amount 
    FROM product JOIN shipped ON (product.id = shipped.product) 
UNION 
    SELECT receipt.badguy, receipt.rdate,notes, amount 
    FROM) A 
1

将您的查询包裹在另一个查询中,其中外部查询只获取所需的总和。这使您的查询子查询

SELECT SUM(amount) FROM (
    SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate, 
      'Delivery' AS Legend, -price*quantity AS amount 
     FROM product JOIN shipped ON (product.id = shipped.product) 
    UNION 
    SELECT receipt.badguy, receipt.rdate,notes, amount 
    FROM <...> 
)