我正在尝试在普及数据库上运行此查询
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&gt;的组结果? 20140101在那里有子结果?
我的查询也提取了那些有in_date&gt;的结果。 20140101
我做错了吗?
我得到的样本输出采用这种格式
cust_no cust_name amount
A a1 500
B b1 500
C c1 1000
我想用cust_no&#39; A&#39;排除此记录。因为它在20140202中与in_date进行了交易
在我的原始数据中考虑我有像
这样的记录cust_no cust_name amount in_date
A a1 100 20130203
A a1 400 20130101
A a1 1000 20140503
答案 0 :(得分:1)
您需要根据一组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和过滤器,其中右表为空)但这有点......粗略的感觉?...因为你似乎允许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;
结合LEFT JOIN
的{{1}}是消除您不想要的记录的部分。
答案 1 :(得分:0)
我认为你需要将日期常量指定为日期,除非你真的想要处理整数。
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;
答案 2 :(得分:0)
我不明白你到底需要什么,
但似乎你混合了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;