[英]Single query to split out data of one column, into two columns, from the same table based on different criteria [SQL]
[英]sql query to sum the columns of 2 table based on the column whose data is different
经过大量的努力使sql查询最终陷入混乱,到目前为止,我所做的是这是table1
select bill_no='2016-2017', B_id, COALESCE(sum(amount-gr),0) as amount, COALESCE (sum(tax),0) as tax, COALESCE(sum(amount_paid),0) as amount_paid, COALESCE(sum(gr),0) as gr,'sun4269' as forUser from tbl_addbill
where forUser='sun4269' and bill_date between '2016-04-01' and '2017-03-31' group by B_id;
bill_no B_id amount tax amount_paid gr forUser
2016-2017 B-1 34875 0 0 0 sun4269
2016-2017 L-1 21014 0 19363 0 sun4269
2016-2017 P-1 10217 0 0 0 sun4269
2016-2017 S-1 30000 0 14000 0 sun4269
2016-2017 T-1 66237 0 21426 0 sun4269
这就是表2
select bill_no,B_id,amount,tax,amount_paid,gr,forUser from tbl_addbill where forUser='sun4269' and bill_date is null and bill_no='2015-2016'
bill_no B_id amount tax amount_paid gr forUser
2015-2016 K-1 181523 0 22159 0 sun4269
2015-2016 L-1 25266 0 4644 0 sun4269
2015-2016 P-1 122383 0 122383 113162 sun4269
2015-2016 A-1 38367 1827 0 0 sun4269
2015-2016 S-1 698262 18575 577120 113449 sun4269
可以看出,表1和表2中的列“ B_id”具有相同以及不同的值(L-1在重复,但B-1在不重复),如果L-1在表中重复,我想要的是,然后在两个表中将金额,已付金额,税金,gr总和与“ 2016-2017”相加,如果B-1在任何表中都是唯一的,则该值也应为“ 2016-2017”
UNION
您的Table 1和Table查询,并执行GROUP BY
的和相关的聚合函数UNION
“d表。
如果仅从table1和table2的UNION
开始,您将明白我的意思,因为结果将是一个表,其中将包含table1和table2的所有行; 然后,您可以添加GROUP BY B_id
和所需的聚合函数(例如SUM()
)。
不确定您要寻找的是什么,但是有条件的聚合会在这里有所帮助吗?
select..., sum(case when bill_date between '2016-04-01' and '2017-03-31'then amount-gr else null end) [2016billdata],
sum(case when bill_date between '2015-04-01' and '2016-03-31'then amount-gr else null end) [2015billdata]....from tbl_addbill
group by...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.