简体   繁体   English

MySQL中两个系列的区别

[英]Difference of two series in MySQL

I have a table with the following fields in MySQL: date, Value, Type. 我在MySQL中有一个包含以下字段的表:日期,值,类型。

Type can be either exports or imports. 类型可以是出口或进口。 I want a query that returns the trade deficit (exports-imports) for each month. 我想要一个查询,该查询返回每个月的贸易赤字(进出口)。 Is this possible with a single query? 一个查询就能做到吗?

You should store your date as a year/month/day in separate columns, or have some way to easily link to a table that lets you do, otherwise you have to do slow calculations on every date column to work out the month. 您应该将日期以年/月/日的形式存储在单独的列中,或者可以通过某种方式轻松链接到允许您执行此操作的表,否则必须对每个date列进行缓慢的计算才能得出月份。 I'll leave it like you've got it for now, but I would suggest storing dates differently to make this calculation easier (if you only ever group by month, then an extra column that stores the result of EXTRACT(YEAR_MONTH FROM date) would make it much quicker overall. 我会像现在一样保留它,但我建议您以不同的方式存储日期,以使此计算更容易(如果您仅按月分组,则需要一个额外的列来存储EXTRACT(YEAR_MONTH FROM date)整体上会更快。

Assuming "Value" is some kind of numeric: 假设“值”是某种数字:

SELECT
    EXTRACT(YEAR_MONTH FROM date) AS month,
    SUM(
        CASE Type
           WHEN 'export' THEN Value
           ELSE -1 * Value
        END
    ) AS trade_deficit
FROM
    mytable
GROUP BY 
    EXTRACT(YEAR_MONTH FROM date)

(I haven't tested this, and there may be some syntax mixups, but it should work) (我还没有测试过,可能会有一些语法混淆,但是应该可以)

I don't think you can do this in one query, because you need 2 different WHERE clauses. 我认为您无法在一个查询中执行此操作,因为您需要2个不同的WHERE子句。

You can retrieve the exports with the following query: 您可以使用以下查询检索导出:

SELECT SUM(VALUE) FROM table WHERE MONTH(date) = month AND YEAR(date) = year AND Type = 'exports'

You can retrieve the imports with the following query: 您可以使用以下查询检索导入:

SELECT SUM(VALUE) FROM table WHERE MONTH(date) = month AND YEAR(date) = year AND Type = 'imports'

This assumes that Value is a numeric field and date is a DATETIME or a DATE field. 假设Value是一个数字字段,而date是DATETIME或DATE字段。

Sorry for the SQL on one line, but I don't know how to line break in the code sample. 对不起,对于一行SQL而言,但是我不知道如何在代码示例中进行换行。

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

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