[英]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.