我有带有数据的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的新手,却没有得到这样的结果。请帮帮我。
答案 0 :(得分:1)
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
答案 1 :(得分:0)
我是条件聚合的忠实拥护者
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;