MySQL查询帮助输出生成值列

时间:2016-05-20 14:57:09

标签: mysql sql

我不熟悉SQL或MySQL查询。我有一张名为Payments的桌子。它的数据存储如下所示。

| Date       | Payment-Type | Money   |
+------------+--------------+---------+
| 2016-05-18 |       Credit | 1619929 |
| 2016-05-18 |        Debit |   35195 |
| 2016-05-18 |         Cash |   10017 |
| 2016-05-18 |       Points |      12 |
| 2016-05-17 |       Credit | 1664529 |
| 2016-05-17 |        Debit |  286404 |
| 2016-05-17 |         Cash |   73244 |
| 2016-05-17 |       Points |      38 |

我在尝试进行以下面显示的以下方式输出数据的查询时遇到问题。我已经尝试在select之后使用if语句,但这使我在与if无关的其他列中留下了空条目。任何帮助都会很棒。

| Date       | Credit  | Cash   | Debit | Points |
+------------+---------+--------+-------+--------+
| 2016-05-18 | 1619929 | 10017  | 35195 |     12 |
| 2016-05-17 | 1664529 | 286404 | 73244 |     38 |

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合

SELECT Date, 
       SUM(CASE WHEN Payment-Type = 'Credit' THEN Money END) AS Credit,
       SUM(CASE WHEN Payment-Type = 'Cash' THEN Money END) AS Cash,
       SUM(CASE WHEN Payment-Type = 'Debit' THEN Money END) AS Debit,
       SUM(CASE WHEN Payment-Type = 'Points' THEN Money END) AS Points
FROM mytable
GROUP BY Date

答案 1 :(得分:1)

您可以使用条件聚合执行此操作:

select date,
       sum(case when paytype = 'Credit' then money else 0 end) as credit,
       sum(case when paytype = 'Cash' then money else 0 end) as cash,
       sum(case when paytype = 'Debit' then money else 0 end) as debit,
       sum(case when paytype = 'Points' then money else 0 end) as points
from payments
group by date
order by date;