简体   繁体   English

根据一个 select 语句中另一列的不同要求对一列求和多次?

[英]Sum a column multiple times based on different requirements from another column in one select statement?

I want to sum the invoices based on the state column.我想根据状态列对发票进行汇总。 But i dont want to do 50 select statements.但我不想做 50 个选择语句。 and the amount of states I query could vary我查询的状态数量可能会有所不同
My Table我的桌子

|invoice|state|
| 123   | NY  |
| 241   | VA  |
| 533   | WA  |

Can I do something like this:我可以做这样的事情:

$sql="Select SUM(invoice) where state=NY as NY AND where state=VA as VA";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($ny,$va);
$stmt->fetch();
echo $ny;
echo $va;
//result: 123 241

Any ideas would be great!任何想法都会很棒! Do I have to make a select statement that executes in a for loop for each state in the array?我是否必须为数组中的每个状态创建一个在 for 循环中执行的 select 语句? thanks!谢谢!

You can use GROUP BY for get sum by state wise.您可以使用GROUP BY按状态获取总和。
Like喜欢

Select state,SUM(invoice) as Total FROM table_name GROUP BY state  

It will give you SUM on invoices by state wise.它将按州为您提供发票上的 SUM。
May be this will help you.可能这会帮助你。

Maybe you were looking for something like this?也许你正在寻找这样的东西?

SELECT SUM(CASE WHEN state='NY' THEN Invoice ELSE 0 END) AS 'NY',
       SUM(CASE WHEN state='VA' THEN Invoice ELSE 0 END) AS 'VA',
       SUM(CASE WHEN state='WA' THEN Invoice ELSE 0 END) AS 'WA' 
FROM table_name;

This will give you result like:这会给你这样的结果:

+-----+-----+-----+
| NY  | VA  | WA  |
+-----+-----+-----+
| 123 | 241 | 533 |
+-----+-----+-----+

If this is not the result you are looking for, you can add more details to your question like your expected output etc.如果这不是您要查找的结果,您可以为您的问题添加更多详细信息,例如您的预期输出等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM