我有一个数量表。金额分为三种方式:半月,每月和每季度。SQL数据库,查找差异
- 如果量> 10000 =半每月
- 如果量> 5000 =每月
- 如果金额< = 5000 =季刊
在量表中的数据,必须在上述匹配。
如果有任何差异我需要吐出来对我。
我该怎么写这段代码?
我有一个数量表。金额分为三种方式:半月,每月和每季度。SQL数据库,查找差异
在量表中的数据,必须在上述匹配。
如果有任何差异我需要吐出来对我。
我该怎么写这段代码?
嗯,你可以只检查:
select t.*
from t
where ((amount > 10000 and classification <> 'Semi-Monthly') or
(amount <= 10000 and amount > 5000 and classification <> 'Monthly') or
(amount <= 5000 and classification <> 'Quarterly')
);
这将返回的差异。
谢谢!现在似乎很明显。 – Joe
将金额和分类都放在同一个表中,这是一个坏主意。你有多余的数据,这就是为什么你现在担心这两列可能不匹配的原因。
有与适当的范围内的分类单独的表:
table classification ==================== text | range_start | range_end -------------+-------------+---------- Semi-Monthly | 10001 | null Monthly | 5001 | 10000 Quarterly | null | 5000
,并从表中删除的分类。然后根据需要从连接中获取分类:
select m.*, c.text as classification
from mytable m
join classification c on m.amount between coalesce(c.range_start, m.amount)
and coalesce(c.range_end, m.amount);
您已经为MySQL和Oracle添加了标签。你真的在使用哪个数据库?您的表格是否有“金额”列和“分类”列? –
我打算只标记Oracle。是的,它有两个,金额和分类。 – Joe
你是否试图在查询中找到它或在表上设置检查约束? – Nicarus