[英]How can I make this sub query more efficient?
I have been learning more about making my sql queries more efficient, but I don't know if I'm doing this query properly. 我一直在学习有关使我的sql查询更高效的更多信息,但是我不知道我是否在正确执行此查询。
I'm trying to find a set in one group, but not the other group. 我正在尝试在一个小组中找到一组,但不在另一小组中找到。 This is the original query which works:
这是有效的原始查询:
SELECT
cNumber
FROM
[dataset.table]
WHERE
DATE(date) >= '2016-01-01'
AND cNumber NOT IN (
SELECT
cNumber
FROM
[dataset.table]
WHERE
date BETWEEN DATEDIFF(CURRENT_DATE(),-5, "QUARTER")
AND DATEDIFF(CURRENT_DATE(), -1, "QUARTER"))
GROUP BY
1
When I change my query to the one below, I get a larger number of results: 当我将查询更改为以下查询时,将获得大量结果:
SELECT
cNumber
FROM
dataset.table
WHERE
DATE(date) >= '2016-01-01'
AND date NOT BETWEEN DATEDIFF(CURRENT_DATE(), -5, "QUARTER")
AND DATEDIFF(CURRENT_DATE(), -1, "QUARTER")
GROUP BY
1
For this type of query, do I need to include a NOT IN
subquery or should I could I just use the second query? 对于此类查询,我是否需要包括
NOT IN
子查询,还是应该只使用第二个查询?
I think I am confused in the second query by trying to include the AND orderCreationDate NOT BETWEEN
. 我想我在第二个查询中感到困惑,因为尝试包括
AND orderCreationDate NOT BETWEEN
。 I thought that since I'm doing a subquery on the same table, that I would be able to wrap it up into one query. 我以为,由于我正在同一张表上执行子查询,因此可以将其包装到一个查询中。
I think this may do what you want: 我认为这可能会满足您的要求:
SELECT cNumber
FROM [dataset.table]
GROUP BY cnumber
HAVING MAX(DATE(date)) >= '2016-01-01' AND
SUM(CASE WHEN date BETWEEN DATEDIFF(CURRENT_DATE(), -5, "QUARTER") AND
DATEDIFF(CURRENT_DATE(), -1, "QUARTER"))
THEN 1 ELSE 0
END) = 0;
That is, choose cnumber
s that have a record sometime since 2016-01-01 and don't have one in the other period specified. 也就是说,选择
cnumber
1月1日以来某个时间有记录且在指定的其他时间内没有记录的cnumber
。
Whether this is faster or not, I do not know. 我是否知道这是否更快。 You have to try it out.
您必须尝试一下。
for BigQuery (Legacy SQL) try below 对于BigQuery(旧版SQL),请尝试以下方法
SELECT cNumber
FROM [dataset.table]
GROUP BY cNumber
HAVING MAX(DATE(date)) >= '2016-01-01'
AND SUM(CASE
WHEN DATE(date) BETWEEN DATE(DATE_ADD(CURRENT_DATE(), -5, "QUARTER"))
AND DATE(DATE_ADD(CURRENT_DATE(), -1, "QUARTER"))
THEN 1 ELSE 0
END) = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.