简体   繁体   English

基于列的 SQL 中的 SUM 值

[英]SUM Values within SQL based on a column

I have a table like below:我有一张如下表:

在此处输入图片说明

I want to transform the data so that the end product actually looks like this:我想转换数据,使最终产品实际上是这样的:

在此处输入图片说明

This is easily done within Excel but i would like to be able to do this via SQL so i can automate a report.这在 Excel 中很容易完成,但我希望能够通过 SQL 做到这一点,以便我可以自动生成报告。

I have tried the below code which doesn't work:我已经尝试了以下不起作用的代码:

SELECT 
SKU,
SUM(totals,ordered = 'Web') as Web_orders,
SUM(totals,ordered = 'App') as App_orders

FROM A

GROUP BY SKU

This will work:这将起作用:

SELECT 
SKU,
SUM(totals) filter (where ordered='web') as Web_orders,
SUM(totals) filter (where ordered='app') as App_orders
FROM A

GROUP BY SKU
ORDER by SKU;

If you want the uppercase letters you need to surround the column names with "".如果您想要大写字母,您需要用“”将列名括起来。

You can make use of case expressions:您可以使用 case 表达式:

SELECT
  sku,
  SUM(case when ordered = 'web' then totals else 0 end) as "web",
  SUM(case when ordered = 'app' then totals else 0 end) as "app"
FROM A
GROUP BY sku

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

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