[英]Total summary from a sales table
I am new for development. 我是新来的发展。 I have a table in Oracle named tbl_sale
. 我在Oracle中有一个名为tbl_sale
的表。 I have placed the table structure below and i also placed the exact report what i want.Please help me to get this. 我在下面放置了表格结构,我还放置了我想要的确切报告。请帮我得到这个。 I want to show the record where parent=0; 我想显示记录,其中parent = 0;
tbl_sale tbl_sale
ID AMOUNT PARENT
1 100 0
2 125.26 1
3 11 1
4 200 0
5 500 4
6 250 4
7 100 4
8 29 0
Desired output: 所需的输出:
ID AMOUNT PARENT
1 236.26 0
4 1050 0
8 29 0
This is what aggregate function and a GROUP BY
are designed for: 这就是聚合函数和GROUP BY
的目的:
SELECT id, SUM(amount) AS amount, parent
FROM tbl_sale
WHERE parent = 0
GROUP BY id, parent
You can do it this way both in SQL Server and Oracle by leveraging a recursive CTE 您可以利用递归CTE在SQL Server和Oracle中以这种方式进行操作
WITH q(id, amount, parent, top_most) AS
(
SELECT id, amount, parent, id
FROM tbl_sale
WHERE parent = 0
UNION ALL
SELECT t.id, t.amount, t.parent, q.id
FROM tbl_sale t JOIN q
ON t.parent = q.id
)
SELECT top_most id, SUM(amount), MIN(parent) parent
FROM q
GROUP BY top_most
Sample output: 样本输出:
| ID | SUM(AMOUNT) | PARENT | |----|-------------|--------| | 1 | 236.26 | 0 | | 4 | 1050 | 0 | | 8 | 29 | 0 |
Here is SQLFiddle demo ( Oracle ) 这是SQLFiddle演示( Oracle )
Here is SQLFiddle demo ( SQL Server ) 这是SQLFiddle演示( SQL Server )
You you are trying to sum based on the sequence of the source data, which is not guaranteed and is subject to change. 您正在尝试根据源数据的顺序求和,这是不能保证的,可能会发生变化。 You need to redesign tbl_sale
to include an element which is common to the rows that you are trying group. 您需要重新设计tbl_sale
以包含您要分组的行所共有的元素。
tbl_sale_line_tems
ID AMOUNT PARENT sale_id
1 100.00 0 1
2 125.26 1 1
3 11.00 1 1
4 200.00 0 2
5 500.00 4 2
6 250.00 4 2
7 100.00 4 2
8 29.00 0 3
We could now also infer that the parent line-item (0) always has the lowest ID within the group of line items for the sale. 现在,我们还可以推断出,在要出售的订单项组中,父订单项(0)始终具有最低的ID。
select min(ID) as ID
,sum(amount)
,sale_id
from tbl_sale_line_items
group by sale_id;
ID AMOUNT SALE_ID
1 236.26 1
4 1050.00 2
8 29.00 3
Here's another way to do it 这是另一种方式
SELECT
parent_id,
sum(amount)
FROM
( SELECT
case when ts2.id IS NULL then ts1.id else ts2.id end as parent_id,
ts1.amount
FROM
tbl_sale ts1
LEFT JOIN tbl_sale ts2 ON ( ts1.parent = ts2.id )
)
GROUP BY
parent_id
ORDER BY
parent_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.