【发布时间】:2018-11-10 00:46:52
【问题描述】:
我目前有类似的结果
total sales | total cost | total profit | department
----------------------------------------------------
100 50 50 A
80 20 60 B
250 120 130 C
使用表中的列
Invoice_Itemized
itemnum | costper | priceper | quantity | invoice_number
--------------------------------------------------------
Invoice_Totals
invoice_number | datetime
---------------------------
库存
itemnum | dept_id
------------------
部门
dept_id | description
----------------------
使用以下代码
select sum(invoice_itemized.priceper* invoice_itemized.quantity) as "Total Sales",
sum(invoice_itemized.quantity*inventory.cost) as "Total Cost",
sum(invoice_itemized.priceper* invoice_itemized.quantity)-
sum(invoice_itemized.quantity*inventory.cost) as "Total Profit",
departments.description as Department
from invoice_itemized, invoice_totals, inventory, departments
where invoice_itemized.invoice_number=invoice_totals.invoice_number
and year(invoice_totals.datetime)=2018 and month(invoice_totals.datetime)=10
and inventory.itemnum=invoice_itemized.itemnum
and inventory.dept_id=departments.dept_id
and departments.description<>'shop use'
and departments.description<>'none'
and departments.description<>'ingredients'
group by departments.description
order by "total profit" desc
我想要类似的结果
total sales | total cost | total profit | percentage total profit | department
-------------------------------------------------------------------------------
100 50 50 20.83 A
80 20 60 25 B
250 120 130 54.17 C
我遇到的问题是我试图将 SUM-SUM 的分组结果除以相同 SUM-SUM 的总数。我已经尝试过类似于
中提出的建议Percentage from Total SUM after GROUP BY SQL Server
但这似乎对我不起作用。我遇到了绑定错误。有什么建议吗?
【问题讨论】:
-
为什么不起作用?你得到了什么?旁注:请明确列出您的
JOINs,并在ON子句中添加尽可能多的条件,而不是使用逗号分隔的FROM子句,这样更易于阅读和推理。跨度> -
从不在
FROM子句中使用逗号。 始终使用正确、明确、标准JOIN语法。
标签: sql sql-server tsql