简体   繁体   English

如何在SQL查询结果中添加条件?

[英]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/1/17之前的所有数量的总和,因此SQL查询的结果将包括条件日期,即使它不在表中也是如此:

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? 但是如何将日期(03/01/2017)纳入结果?

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. 请注意,这被解释为2017年1月3日-YYYY-MM-DD。 All date constants should be represented as YYYY-MM-DD (it is an ISO standard). 所有日期常量都应表示为YYYY-MM-DD(这是一个ISO标准)。

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. DATE()的使用将其显式转换为日期(而不是字符串)以用于输出目的。

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

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