SQL列之间的绝对值

时间:2008-10-07 05:06:31

标签: python mysql sql oracle postgresql

我有一张看起来像这样的表:

word        big   expensive   smart   fast

dog         9     -10         -20     4
professor   2     4           40      -7
ferrari     7     50          0       48
alaska      10    0           1       0
gnat        -3    0           0       0

+和 - 值与单词相关联,因此教授很聪明,狗也不聪明。阿拉斯加是一个很大的,占其参赛作品总价值的一部分,与gnat相反。

是否有一种很好的方法可以获得距离零最远的数字的绝对值,还有一些标记是绝对值= / =值?相关地,我如何计算给定值的结果是否相对于其他值成比例地大?我会写一些东西来格式化输出效果:“狗:不聪明,可能不贵;教授聪明;法拉利:快速,昂贵;阿拉斯加:大; gnat:可能很小。” (格式化不是问题,只是一个例子,我被困在基础查询上。)

此外,该程序的其余部分是python,所以如果有任何python解决方案与普通的dbapi模块或更抽象的模块,任何帮助赞赏。

5 个答案:

答案 0 :(得分:3)

以big的绝对值列出的单词:

select word, big from myTable order by abs(big)

每个类别的总计:

select sum(abs(big)) as sumbig, 
       sum(abs(expensive)) as sumexpensive,   
       sum(abs(smart)) as sumsmart,
       sum(abs(fast)) as sumfast
  from MyTable;

答案 1 :(得分:2)

从零开始的绝对值:

select max(abs(mycol)) from mytbl
如果值为负,

将为零:

select n+abs(mycol)
  from zzz
 where abs(mycol)=(select max(abs(mycol)) from mytbl);

答案 2 :(得分:1)

问题似乎是你主要想在一行内工作,而这些类型的问题在SQL中很难回答。

我会尝试将您提到的结构转换为更像“原子”的事实表,如

word property value

通过重新设计基础表(如果可能,如果对应用程序的其余部分有意义),或者通过定义为您执行此操作的视图,例如

select word, 'big' as property, big as value from soquestion
UNION ALLL
select word, 'expensive', expensive from soquestion
UNION ALL
...

这允许您询问每个单词的最大值:

select word, max(value), 
    (select property from soquestion t2 
     where t1.word = t2.word and t2.value = max(t1.value))
from soquestion t1
group by word

还是有点尴尬,但大多数逻辑都是在SQL中,而不是你选择的编程语言。

答案 3 :(得分:0)

您可以使用MAX(列)等内置数据库聚合函数吗?

答案 4 :(得分:0)

提出问题有助于澄清问题;这是一个功能,可以更多地了解我想要做的事情。有没有办法表示上面的¶2中的一些内容,或者在SQL或python中更有效的方法,我想在show_distinct中完成什么?

#!/usr/bin/env python

import sqlite3

conn = sqlite3.connect('so_question.sqlite')
cur = conn.cursor()

cur.execute('create table soquestion (word, big, expensive, smart, fast)')
cur.execute("insert into soquestion values ('dog', 9, -10, -20, 4)")
cur.execute("insert into soquestion values ('professor', 2, 4, 40, -7)")
cur.execute("insert into soquestion values ('ferrari', 7, 50, 0, 48)")
cur.execute("insert into soquestion values ('alaska', 10, 0, 1, 0)")
cur.execute("insert into soquestion values ('gnat', -3, 0, 0, 0)")

cur.execute("select * from soquestion")
all = cur.fetchall()

definition_list = ['word', 'big', 'expensive', 'smart', 'fast']

def show_distinct(db_tuple, def_list=definition_list):
    minimum = min(db_tuple[1:])
    maximum = max(db_tuple[1:])
    if abs(minimum) > maximum:
        print db_tuple[0], 'is not', def_list[list(db_tuple).index(minimum)]
    elif maximum > abs(minimum):
        print db_tuple[0], 'is', def_list[list(db_tuple).index(maximum)]
    else:
        print 'no distinct value'

for item in all:
    show_distinct(item)

运行此命令:

    dog is not smart
    professor is smart
    ferrari is expensive
    alaska is big
    gnat is not big
    >>> 
相关问题