gpt4 book ai didi

MySQL - 基于同一表中的行求和列值

转载 作者:IT老高 更新时间:2023-10-28 12:58:02 27 4
gpt4 key购买 nike

我正在尝试根据同一张表中的 ProductID 在新列中获取“现金”、“支票”和“信用卡”总计。

表格 - 付款

+-----------+------------+---------------+--------+
| ProductID | SaleDate | PaymentMethod | Amount |
+-----------+------------+---------------+--------+
| 3 | 2012-02-10 | Cash | 10 |
| 3 | 2012-02-10 | Cash | 10 |
| 3 | 2012-02-10 | Check | 15 |
| 3 | 2012-02-10 | Credit Card | 25 |
| 4 | 2012-02-10 | Cash | 5 |
| 4 | 2012-02-10 | Check | 6 |
| 4 | 2012-02-10 | Credit Card | 7 |
+-----------+------------+---------------+--------+

期望的输出 -

+------------+------+-------+-------------+-------+
| ProductID | Cash | Check | Credit Card | Total |
+------------+------+-------+-------------+-------+
| 3 | 20 | 15 | 25 | 60 |
| 4 | 5 | 6 | 7 | 18 |
+------------+------+-------+-------------+-------+

我已经尝试 LEFT JOINing 同一张表,但没有任何成功。任何建议,将不胜感激。谢谢。

不成功且不完整的尝试 -

SELECT P.ProductID, Sum( PCash.Amount ) AS 'Cash', SUM( PCheck.Amount ) AS 'Check', SUM( PCredit.Amount) AS 'Credit Card' 
FROM Payments AS P
LEFT JOIN Payments AS PCash ON P.ProductID = PCash.ProductID AND PCash.PaymentMethod = 'Cash'
LEFT JOIN Payments AS PCheck ON P.ProductID = PCheck.ProductID AND PCheck.PaymentMethod = 'Check'
LEFT JOIN Payments AS PCredit ON P.ProductID = PCredit.ProductID AND PCredit.PaymentMethod = 'Credit'
WHERE P.SaleDate = '2012-02-10' GROUP BY ProductID;

最佳答案

我认为你让这变得比它需要的复杂一点。

SELECT
ProductID,
SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
-- snip
SUM(Amount) AS Total
FROM
Payments
WHERE
SaleDate = '2012-02-10'
GROUP BY
ProductID

关于MySQL - 基于同一表中的行求和列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805851/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com