我有一個SQLite查詢,它回傳一個用戶名和用戶花了多少錢(由不同表中的 SELECT SUM() 完成)。
| 姓名 | 花費 |
|---|---|
| 亞當 | 700 |
| 麥克風 | 400 |
| 史蒂夫 | 100 |
我有另一個表,其中包含具有相應閾值的折扣金額:
| 門檻 | 折扣 |
|---|---|
| 200 | 5 |
| 400 | 10 |
| 600 | 15 |
我需要找出每個用戶有什么折扣(如果有的話)。所以結果看起來像這樣:
| 姓名 | 花費 | 折扣 | 全部的 |
|---|---|---|---|
| 亞當 | 700 | 15 | 595 |
| 麥克風 | 400 | 10 | 360 |
| 史蒂夫 | 100 | 0 | 100 |
uj5u.com熱心網友回復:
您需要LEFT將查詢連接到第二個表和聚合:
SELECT t1.name, t1.Spent,
COALESCE(MAX(t2.Discount), 0) Discount,
t1.Spent * (1 - 0.01 * COALESCE(MAX(t2.Discount), 0)) Total
FROM (SELECT name, SUM(Spent) Spent FROM table1 GROUP BY name) t1
LEFT JOIN table2 t2 ON t2.Treshold <= t1.Spent
GROUP BY t1.name;
請參閱演示。
uj5u.com熱心網友回復:
我很急。對不起。
with a as (
select name, sum(spent) spe
from test1
group by name)
select a.name
, a.spe
, max(tres)
, max(disc)
, spe -spe * (0 || '.' || disc) total
from test2, a
where tres <= a.spe
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446902.html
