如何在 SQL 中获取一行和三列(使用每个信使的成本总和)?
Posted
技术标签:
【中文标题】如何在 SQL 中获取一行和三列(使用每个信使的成本总和)?【英文标题】:How to get one line and Three colums in SQL (using the sum of costs for each menssenger)? 【发布时间】:2021-03-12 06:32:41 【问题描述】:table screenshot
以下查询让我得到 3 行,但这不是我想要得到的,我想要得到 1 行和 3 列,你能帮我吗?
Select NoMess,
case
when (NoMess = "1") Then (SELECT SUM (Port) from commande where NoMess = "1")
when (NoMess = "2") Then (SELECT SUM (Port) from commande where NoMess = "2")
when (NoMess = "3") Then (SELECT SUM (Port) from commande where NoMess = "3")
End as Port
From Commande
Group by NoMess
【问题讨论】:
【参考方案1】:您可以使用条件聚合来做到这一点:
SELECT
SUM(CASE WHEN NoMess = '1' THEN Port ELSE 0 END) AS column1,
SUM(CASE WHEN NoMess = '2' THEN Port ELSE 0 END) AS column2,
SUM(CASE WHEN NoMess = '3' THEN Port ELSE 0 END) AS column3
FROM Commande
【讨论】:
以上是关于如何在 SQL 中获取一行和三列(使用每个信使的成本总和)?的主要内容,如果未能解决你的问题,请参考以下文章