计算具有两个不同日期条件的列中的所有行

时间:2020-03-30 07:52:08

标签: mysql sql date group-by mariadb

我正在尝试将两个具有日期条件的计数查询(以下条件)转换为一个查询。

The replica master 0 exited with a non-zero status of 1. Traceback (most recent call last): File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/root/.local/lib/python3.7/site-packages/trainer/final_task.py", line 114, in <module> train_model(HPARAMS) File "/root/.local/lib/python3.7/site-packages/trainer/final_task.py", line 55, in train_model (train_data, train_labels) = data.create_data_with_labels("data/train/") File "/root/.local/lib/python3.7/site-packages/trainer/data.py", line 13, in create_data_with_labels mug_dirs = [f for f in os.listdir(image_dir) if not f.startswith('.')] FileNotFoundError: [Errno 2] No such file or directory: 'data/train/' To find out more about why your job exited please check the logs: https://console.cloud.google.com/logs/viewer?project=1047296516162&resource=ml_job%2Fjob_id%2Fml6_run_25&advancedFilter=resource.type%3D%22ml_job%22%0Aresource.labels.job_id%3D%22ml6_run_25%22

Following the advice of another answer我创建了以下内容,但这似乎在语法上不起作用,我也不知道为什么。还有另一种方法吗?我找不到与此类似的问题

SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 1 DAY)
SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 2 DAY)

2 个答案:

答案 0 :(得分:1)

您需要条件聚合。我将查询语句如下:

<img src="{{ product.image_url }}" alt="...">

详细信息:

  • 这使用了MySQL的一个不错的功能,即在数字上下文中将错误/真实条件评估为SELECT SUM( timedate >= CURRENT_DATE - INTERVAL 1 DAY and timedate < CURRENT_DATE ) AS testcount1, SUM( timedate >= CURRENT_DATE - INTERVAL 2 DAY and timedate < CURRENT_DATE- INTERVAL 1 DAT ) AS testcount2 FROM orders

  • 0/1列上未应用任何日期函数:相反,我们进行基准日期比较。由于数据库可能可以利用datetime列上的索引

  • ,因此效率更高

您可能还想向查询添加timedate子句:

WHERE

答案 1 :(得分:1)

您缺少IF表达式的输出值。另外,您应该使用CURRENT_DATE(),这样就不必转换为DATE

SELECT 
    SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY, 1, 0)) AS testcount1,
    SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY, 1, 0)) AS testcount2
FROM 
    orders

请注意,MySQL在数字上下文中将布尔表达式视为1true)或0false),因此您实际上可以SUM表达式而无需使用IF

SELECT 
    SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY) AS testcount1,
    SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY) AS testcount2
FROM 
    orders