我有包含数据的BillItem表。下面是表格
+------------+--------+-----------+-------------+-----------+-------------+
| BillItemId | BillId | PayTypeId | GrossAmount | TaxAmount | TotalAmount |
+------------+--------+-----------+-------------+-----------+-------------+
| 430 | 415 | 56 | 60.00 | 9.90 | 69.90 |
| 431 | 416 | 57 | 3125.00 | 156.25 | 3281.25 |
| 432 | 417 | 57 | 6500.00 | 325.00 | 6825.00 |
| 433 | 418 | 57 | 1750.00 | 87.50 | 1837.50 |
| 434 | 419 | 58 | 2220.00 | 111.00 | 2331.00 |
| 435 | 416 | 58 | 1776.00 | 88.80 | 1864.80 |
| 436 | 420 | 61 | 6000.00 | 300.00 | 6300.00 |
| 437 | 421 | 60 | 5270.00 | 263.50 | 5533.50 |
| 438 | 421 | 61 | 3600.00 | 180.00 | 3780.00 |
+------------+--------+-----------+-------------+-----------+-------------+但是从BillItem表中我想要如下表所示的结果
+--------+-------+---------+---------+---------+---------+-------------+-----------+-------------+
| BillId | 56 | 57 | 58 | 60 | 61 | GrossAmount | TaxAmount | TotalAmount |
+--------+-------+---------+---------+---------+---------+-------------+-----------+-------------+
| 415 | 60.00 | 0 | 0 | 0 | 0 | 60.00 | 9.90 | 69.90 |
| 416 | 0 | 3125.00 | 1776.00 | 0 | 0 | 4901.00 | 245.05 | 5146.05 |
| 417 | 0 | 6500.00 | 0 | 0 | 0 | 6500.00 | 325.00 | 6825.00 |
| 418 | 0 | 1750.00 | 0 | 0 | 0 | 1750.00 | 87.50 | 1837.50 |
| 419 | 0 | 0 | 2220.00 | 0 | 0 | 2220.00 | 111.00 | 2331.00 |
| 420 | 0 | 0 | 0 | 0 | 6000.00 | 6000.00 | 300.00 | 6300.00 |
| 421 | 0 | 0 | 0 | 5270.00 | 3600.00 | 8870.00 | 443.50 | 9313.50 |
+--------+-------+---------+---------+---------+---------+-------------+-----------+-------------+如结果表所示,需要数据为BillId及其相关分量之和。我是sql的新手,不知道如何找到这样的结果。请帮帮我。
发布于 2018-08-31 17:26:55
select * from
(
BillId,sum(GrossAmount),sum(TaxAmount),sum(TotalAmount),PayTypeId
from BillItem
group by BillId
)
as tablo
pivot
(
sum(GrossAmount)
for PayTypeId in ([56],[57],[58],[59],[60],[61])
) as p
order by BillId发布于 2018-08-31 18:47:20
我是条件聚合的铁杆粉丝:
select BillId,
sum(case when PayTypeId = 56 then GrossAmount else 0 end) as grossamount_56,
sum(case when PayTypeId = 57 then GrossAmount else 0 end) as grossamount_57,
sum(case when PayTypeId = 58 then GrossAmount else 0 end) as grossamount_58,
sum(case when PayTypeId = 59 then GrossAmount else 0 end) as grossamount_59,
sum(case when PayTypeId = 60 then GrossAmount else 0 end) as grossamount_60,
sum(case when PayTypeId = 61 then GrossAmount else 0 end) as grossamount_1,
sum(GrossAmount) as grossamount,
sum(TaxAmount) as taxamount,
sum(TotalAmount) as totalamount
from BillItem bi
group by BillId;https://stackoverflow.com/questions/52112140
复制相似问题