[英]pervasive query with group by issue
我正在尝试在普及数据库上运行此查询
select cust_no,cust_name,sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null and number is not null and bvtotal > 1000 and in_date < 20140101
group by cust_no,cust_name
order by sum(bvtotal) desc;
如何排除子结果中in_date> 20140101的组结果?
我也有此查询正在获取in_date> 20140101的那些结果
难道我做错了什么 ?
我得到的样本输出是这种格式
cust_no cust_name amount
A a1 500
B b1 500
C c1 1000
我想使用cust_no'A'排除此记录,因为它在20140202中具有与in_date的事务
考虑在我的原始数据中,我有类似的记录
cust_no cust_name amount in_date
A a1 100 20130203
A a1 400 20130101
A a1 1000 20140503
您需要根据一组ID排除所有记录。 通常,您可以使用子查询来执行此操作:
SELECT cust_no,
cust_name,
sum(bvtotal) AS Amount
FROM sales_history_header
WHERE cust_no IS NOT NULL
AND number IS NOT NULL
AND bvtotal > 1000
AND cust_no NOT IN (
SELECT cust_no
FROM sales_history_header
WHERE in_date >= 20140101
AND cust_no IS NOT NULL
)
GROUP BY cust_no,
cust_name
ORDER BY sum(bvtotal) DESC;
子查询的AND cust_no IS NOT NULL
部分是为了避免NOT IN
和NULL
值出现问题。 如果将其重写为NOT EXISTS
相关子查询,则可能会获得更好的性能,但以我的经验,MySQL在这些方面相当糟糕。
另一种选择是更明确的自我防联接方法(LEFT JOIN和filter,其中右表为null),但这有点...粗略的感觉?...因为您似乎允许cust_no
为NULL
并且它是一个查询正在聚合,因此感觉就像您不得不担心会增加行:
SELECT s1.cust_no,
s1.cust_name,
sum(s1.bvtotal) AS Amount
FROM sales_history_header s1
LEFT JOIN (
SELECT cust_no
FROM sales_history_header
WHERE cust_no IS NOT NULL
AND number IS NOT NULL
AND bvtotal > 1000
AND in_date >= 20140101) s2
ON s2.cust_no = s1.cust_no
WHERE s1.cust_no IS NOT NULL
AND s1.number IS NOT NULL
AND s1.bvtotal > 1000
AND s2.cust_no IS NULL
GROUP BY cust_no,
cust_name
ORDER BY sum(bvtotal) DESC;
WHERE [...] s2.cust_no IS NULL
LEFT JOIN
与WHERE [...] s2.cust_no IS NULL
组合在一起,可以消除不需要的记录。
我认为您需要将日期常数指定为日期,除非您确实要处理整数。
select cust_no,cust_name,sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null and number is not null and bvtotal > 1000 and in_date < '2014-01-01'
group by cust_no,cust_name
order by sum(bvtotal) desc;
我不明白你到底需要什么
但是似乎您混合了INT和DATE类型。
因此,如果您的in_date
字段的类型为DATE
select
cust_no,
cust_name,
sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null
and number is not null
and bvtotal > 1000
and in_date < DATE('2014-01-01')
group by cust_no,cust_name
order by sum(bvtotal) desc;
如果您的in_date
字段键入TIMESTAMP
select
cust_no,
cust_name,
sum(bvtotal) as Amount
from sales_history_header
where cust_no is not null
and number is not null
and bvtotal > 1000
and in_date < TIMESTAMP('2014-01-01 00:00:00')
group by cust_no,cust_name
order by sum(bvtotal) desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.