简体   繁体   中英

How to add a condition to the result of an SQL query?

I have a table, somewhat like this

date_of_order|quantity
01/01/17     | 1 
02/01/17     | 1
04/01/17     | 1
05/01/17     | 1

I need a sum of all quantities before 03/01/17, so the result of the SQL query would include the condition date even if it is not in the table, something like this:

03/01/17 2

I know how to show the sum:

 SELECT SUM(quantity) from table_name WHERE date_of_order < '2017-01-03'

but how to include the date(03/01/2017) into the result?

Thanks!

只需将其添加为单独的列:

SELECT '2017-01-03' as DateStart, SUM(quantity) from table_name WHERE date_of_order < 2017-01-03

Date constants should be in single quotes:

SELECT SUM(quantity)
FROM table_name
WHERE date_of_order < '2017-01-03';

Note that this is interpreted as January 3rd, 2017 -- YYYY-MM-DD. All date constants should be represented as YYYY-MM-DD (it is an ISO standard).

If you want the value in the result, put it therre:

SELECT DATE('2017-01-03') as thedate, SUM(quantity)
FROM table_name
WHERE date_of_order < '2017-01-03';

The use of DATE() explicitly converts it to a date (rather than a string) for output purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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