对于某些类别,我的查询会返回每个月的销售列总计和每月的购买总额。
SELECT theMonth,
sum(Sales) as sumSales,
sum(Saleswotax) as sumSaleswotax,
sum(Purchases) as sumPurchases,
sum(Purchaseswotax) as sumPurchaseswotax
FROM ( SELECT date_format(saledate, '%Y-%m') AS theMonth,
sales.cost as Sales,
ROUND(sales.cost*0.85, 2) AS Saleswotax,
0 AS Purchases,
0 AS Purchaseswotax
FROM sales, products
WHERE sales.product = products.name
AND category='Food'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth,
0 as Sales,
0 AS Saleswotax,
purchases.cost as Purchases,
ROUND(purchases.cost*0.85, 2) AS Purchaseswotax,
FROM purchases) AS all_costs
group by theMonth
我试图在我的查询中返回一个列(实际上不存在于表中),这只是对现有表的计算。即saleswotax和purchaseswotax列。
我正在使用一个函数,并将其作为名称返回...为什么它不起作用?
答案 0 :(得分:1)
在联盟中,您使用0作为销售和购买列,但是也没有使用-wotax列。他们需要匹配联盟才能正常工作(我想你知道,因为你是为销售和购买而做的)。
答案 1 :(得分:0)
上次我看到,MySQL中的计算字段没有声明性支持。 您必须向表中添加计算列并使用UPDATE / INSERT触发器填充它们。或者使用其他计算列创建视图。
答案 2 :(得分:0)
你需要删除UNION后半部分AS Purchasewotax
之后的逗号:
SELECT theMonth,
sum(Sales) as sumSales,
sum(Saleswotax) as sumSaleswotax,
sum(Purchases) as sumPurchases,
sum(Purchaseswotax) as sumPurchaseswotax
FROM ( SELECT date_format(saledate, '%Y-%m') AS theMonth,
sales.cost as Sales,
ROUND(sales.cost*0.85, 2) AS Saleswotax,
0 AS Purchases,
0 AS Purchaseswotax
FROM sales, products
WHERE sales.product = products.name
AND category='Food'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth,
0 as Sales,
0 AS Saleswotax,
purchases.cost as Purchases,
ROUND(purchases.cost*0.85, 2) AS Purchaseswotax
FROM purchases) AS all_costs
GROUP BY theMonth