简体   繁体   English

SQL-对另一个查询的结果执行查询?

[英]SQL - Performing a query on a result from another query?

I have a column(varchar) with date values, I need to find those dates which are expiring in next 30 days. 我有一个带有日期值的列(varchar),我需要查找在接下来的30天内到期的那些日期。

ExpiringDate
===================
20171208,
20171215,samples
20171130,tested
N/A
No
(empty row)

So, First I need to get values before comma. 因此,首先我需要在逗号前获取值。 On the resultset, I need to filter out rows that has only numbers(no 'N/A' or 'No' or empty rows) & then I need to filter those dates which are expiring in next 30 days. 在结果集上,我需要过滤出仅包含数字的行(没有“ N / A”或“ No”或空行),然后我需要过滤出将在30天后到期的日期。

Edited 已编辑

I have tried the following & resultset seems to be inappropriate 我尝试了以下&结果集似乎不合适

SELECT
  DocName,
  CategoryName,
  AttributeName,
  CAST(SUBSTRING_INDEX(AttributeValue, ',', 1) AS DATE) AS ExpiredDate
FROM myDB
WHERE (AttributeName = 'Date of last vessel OVID' OR AttributeName = 'Next Statutory docking' OR
       AttributeName = 'Last statutory docking') AND AttributeValue LIKE '%[^0-9]%' AND
      DATEDIFF(now(), AttributeValue) <= 30;

Because you are not only storing dates as text, but mixing those dates with entirely non date information, this complicates things. 因为您不仅将日期存储为文本,而且将这些日期与完全非日期的信息混合在一起,这使事情变得复杂。 In this case, we can do two checks, one to ensure that the record starts with an actual expected date, and the second to make sure that the date diff is within 30 days from now. 在这种情况下,我们可以进行两项检查,一项是确保记录以实际的预期日期开始,另一项是确保日期差异在从现在起的30天内。

SELECT ExpiringDate
FROM
(
    SELECT ExpiringDate
    FROM yourTable
    WHERE ExpiringDate REGEXP '^[0-9]{8}'
) t
WHERE
    DATEDIFF(LEFT(ExpiringDate, 8), NOW()) BETWEEN 0 AND 30;

Note that I use a subquery to first remove rows that do not even have a parseable date. 请注意,我首先使用子查询删除甚至没有可解析日期的行。 The reason for this is that DATEDIFF will error out if not passed valid dates for both parameters. 这样做的原因是,如果未传递两个参数的有效日期, DATEDIFF将出错。

Demo 演示版

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

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