我有一个名为 demo 的表,结构如下
+------------+-------------+--------+
| CustomerID | Transaction | Points |
+------------+-------------+--------+
| 1 | Transfer | 230 |
| 2 | Accrual | 189 |
| 5 | Accrual | 121 |
| 1 | Usage | 306 |
| 3 | Accrual | 467 |
| 1 | Expiry | 328 |
| 2 | Accrual | 343 |
| 2 | Usage | 475 |
| 3 | Transfer | 194 |
| 1 | Accrual | 459 |
| 5 | Accrual | 314 |
+------------+-------------+--------+
所以我想根据交易类型得到不同标准的点数 所以我做的就像
SELECT *
FROM
(select sum(points) AS TransferedPoints from Demo where transaction="Transfer" ) AS TTbl,
(select sum(points) AS PointsAccruals from Demo where transaction="Accrual" ) AS ACTbl,
(select sum(points) AS PointsUsage from Demo where transaction="Usage") AS UsTbl,
(select sum(points)AS ExpiredPoints from Demo where transaction="Expiry" ) AS ExTbl;
结果就像
+------------------+--------------------+-----------------+-------------------+
| TransferedPoints | PointsAccruals | PointsUsage | ExpiredPoints |
+------------------+--------------------+-----------------+-------------------+
| 424 | 1893 | 781 | 328 |
+------------------+--------------------+-----------------+-------------------+
这很好,但我想通过ID将其分解,我不知道如何做到这一点,我希望最终结果看起来像这样
+-------------+----------------------+--------------------+-----------------+-------------------+
| Customer ID | TransferedPoints | PointsAccruals | PointsUsage | ExpiredPoints |
+-------------+----------------------+--------------------+-----------------+-------------------+
| 1 | 230 | 459 | 306 | 328 |
| 2 | | 532 | 475 | |
| 3 | 194 | 467 | | |
| 5 | | 435 | | |
+-------------+----------------------+--------------------+-----------------+-------------------+
由于
答案 0 :(得分:2)
使用条件聚合!
SELECT ID, SUM(IIF(transaction = "Transfer", points, 0)) AS TransferedPoints,
SUM(IIF(transaction = "Accrual", points, 0)) AS AccrualPoints,
SUM(IIF(transaction = "Usage", points, 0)) AS UsagePoints,
SUM(IIF(transaction = "Expiry", points, 0)) AS ExpiryPoints
FROM DEMO
GROUP BY ID;
或者,如果您可以处理四行,请使用GROUP BY
:
select id, transaction, sum(points)
from demo
group by id, transaction;