[英]how do i pull mysql data with case statements into separate columns
I have table as follows: 我的表如下:
sales: customerid, invoice, saledate, amount
销售:客户编号,发票,销售日期,金额
journal: reference, date, type, amount日记帐:参考,日期,类型,金额
customers: customerid, customername客户:customerid,customername
I need to pull out data from this table and show in following format: 我需要从该表中提取数据并以以下格式显示:
customer name | jan sales| feb sales| march sales| april sales|
and so on 等等
I am trying the following query:- 我正在尝试以下查询:
SELECT
customers.customername AS customer_name,
CASE WHEN EXTRACT(MONTH FROM journal.date) = 1 THEN SUM(journal.amount) AS january_sales ELSE 0 END,
CASE WHEN EXTRACT(MONTH FROM journal.date) = 1 THEN SUM(journal.amount) AS feb_sales ELSE 0 END,
CASE WHEN EXTRACT(MONTH FROM journal.date) = 1 THEN SUM(journal.amount) AS march_sales ELSE 0 END
FROM customers
JOIN sales ON sales.customerid = customers.customerid
JOIN journal ON journal.reference = sales.invoice
WHERE
journal.type = 'sale' AND
journal.date BETWEEN '2013-01-01' AND '2013-03-31' GROUP BY
customers.customername
i am not able to get this query to work. 我无法使该查询正常工作。 any help is appreciated.
任何帮助表示赞赏。
Use CASE
in side the SUM
在
SUM
使用CASE
SELECT
customers.customername AS customer_name,
SUM(
CASE
WHEN EXTRACT(MONTH FROM journal.date) = 1
THEN journal.amount
ELSE 0
END
) AS january_sales,
SUM(
CASE
WHEN EXTRACT(MONTH FROM journal.date) = 1
THEN journal.amount
ELSE 0
END
) AS feb_sales,
SUM(
CASE
WHEN EXTRACT(MONTH FROM journal.date) = 1
THEN journal.amount
ELSE 0
END
) AS march_sales
FROM
customers
JOIN sales
ON sales.customerid = customers.customerid
JOIN journal
ON journal.reference = sales.invoice
WHERE journal.type = 'sale'
AND journal.date BETWEEN '2013-01-01'
AND '2013-03-31'
GROUP BY customers.customername
I think this is what you want: 我认为这是您想要的:
SELECT c.customername AS customer_name,
sum(CASE WHEN month(j.date) = 1 THEN j.amount end) AS january_sales,
sum(CASE WHEN month(j.date) = 2 THEN j.amount end) AS feb_sales,
sum(CASE WHEN month(j.date) = 3 THEN j.amount end) AS march_sales
FROM customers c JOIN
sales s
ON s.customerid = c.customerid JOIN
journal j
ON j.reference = s.invoice
WHERE
j.type = 'sale' AND
j.date BETWEEN '2013-01-01' AND '2013-03-31'
GROUP BY c.customername;
Your case
statement was all messed up. 您的
case
陈述书被弄糟了。 For instance, it had the column alias inside the statement rather than after it. 例如,它在语句内部而不是后面具有列别名。 I made a couple other changes.
我进行了其他一些更改。 I think
month()
is easier than extract(month)
(a matter of opinion because the latter is ANSI standard). 我认为
month()
比extract(month)
容易extract(month)
一种观点,因为后者是ANSI标准)。 I also put in table aliases to make the query easier to read. 我还添加了表别名,以使查询更易于阅读。
Note that you should probably be looking at the year value as well as the month, in case the range for the query extends over 12 months. 请注意,如果查询范围超过12个月,则可能应查看年份值和月份。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.