SQL 根据固定值使用新列值进行查询
我有两个表 table1 和 table2
table1 具有列:
id name value
1 name1 0.5
2 name2 1.9
3 name3 2.6
4 name4 0.2
....
999 name999 4.7
table2 具有我想要创建结果的列
id risk value
1 low 0.5
2 medium 1.5
3 high 2.5
,例如: (low >=0.5 和 <1.5 ,medium >=1.5 和 <2.5,high >2.5 )并从较高的值到较小的值
1 name999 high
2 name3 high
3 name2 medium
4 name1 low
加法
另一个问题:
table1 有列:
id name value
1 name1 0.5
2 name2 1.9
3 name3 2.6
4 name4 0.2
....
999 name999 4.7
假设在列名称中我们有 test1 和 test2,并且我们希望 test1 的结果始终非常低,而 test2 的结果始终非常高。那么要进行什么 sql 修改才能获得此结果?
1 test2 very high
2 name999 high
3 name3 high
4 name2 medium
5 name1 low
6 test1 very low
我们是否还必须编辑 table2 才能按风险对上述结果进行排序?
I have two tables table1 and table2
table1 has the columns:
id name value
1 name1 0.5
2 name2 1.9
3 name3 2.6
4 name4 0.2
....
999 name999 4.7
table2 has the columns
id risk value
1 low 0.5
2 medium 1.5
3 high 2.5
I want to create a result for example: (low >=0.5 and <1.5 , medium >=1.5 and <2.5, high >2.5) and from higher value to smaller value
1 name999 high
2 name3 high
3 name2 medium
4 name1 low
Addition
Another one question:
table1 has the columns:
id name value
1 name1 0.5
2 name2 1.9
3 name3 2.6
4 name4 0.2
....
999 name999 4.7
suppose in column name we have test1 and test2 and we want in the result for test1 to always be very low and for test2 very high.So what will be the sql modification to have this result?
1 test2 very high
2 name999 high
3 name3 high
4 name2 medium
5 name1 low
6 test1 very low
do we have to edit table2 also for ordering the above result by risk?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在 table2 中指定上限和下限,而不是尝试执行某种最近数字查找,这会容易得多。它可以很简单,
如果您坚持使用最近的数字查找,您可以通过编写包含
ABS(a.value - b.value)
,按该字段排序并选择前 1 个,但此时没有简单的方法进行连接。您可能会从游标内将记录插入到临时表中,从临时表中进行选择,然后将其删除 - 只需对第二个表进行一个小更改就可以避免这种混乱。This would be much easier if you specify the upper and lower bounds in table2 instead of trying to perform some kind of nearest-number lookup. It could be as simple as
If you insist on using the nearest-number lookup, you can determine which value from table1 is closest to table2 by writing a select which includes
ABS(a.value - b.value)
, ordering by that field and selecting the top 1, but there's no easy way to do the join at that point. You'll likely be inserting records into a temp table from within a cursor, selecting from the temp table and then dropping it - a big nasty mess that could be avoided by simply making one small change to your second table.