SQL:数据过滤器
我有一个包含数据的BillItem表。下面是表格SQL:数据过滤器,sql,sql-server,Sql,Sql Server,我有一个包含数据的BillItem表。下面是表格 +------------+--------+-----------+-------------+-----------+-------------+ | BillItemId | BillId | PayTypeId | GrossAmount | TaxAmount | TotalAmount | +------------+--------+-----------+-------------+-----------+------------
+------------+--------+-----------+-------------+-----------+-------------+
| 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新手,不知道如何找到这样的结果。请帮助我。我非常喜欢条件聚合:
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
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;
您正在使用哪个dbms?MS SQL server..最好将示例数据显示为。屏幕截图中的数据不能用于通过复制和粘贴设置测试台。看起来您已经有了表;你可以将它们转换成网站可以处理的文本。如果PayTypeId不固定,那么我们可以编写查询来获取括号中的值吗?我还需要PayType值的总和,如果它添加了多次实际上,PayTypeId不固定,它是动态的