将单列SQL SELECT结果列表转换为单行

时间:2010-11-10 05:58:26

标签: sqlite sql

我该如何发表声明:

SELECT column1 FROM db WHERE country in ('USA','BRA','CHN') and commodity='pork'

返回

value1, value2, value3 (where value1 is for USA, value2 for BRA, value3 for CHN)

到目前为止,我得到的最好的是一个列,所有值都从数据库中提取出来。

9 个答案:

答案 0 :(得分:2)

您可能正在寻找GROUP_CONCAT()函数:

http://www.sqlite.org/lang_aggfunc.html

答案 1 :(得分:2)

您可以执行以下操作:

Select a.column1,b.column2,c.column3 from
(SELECT column1 FROM db WHERE country ='USA' and commodity='pork') as a,
(SELECT column1 FROM db WHERE country ='BRA' and commodity='pork') as b,
(SELECT column1 FROM db WHERE country ='CHN' and commodity='pork') as c

答案 2 :(得分:1)

使用sql pivot。这对你有帮助。

答案 3 :(得分:1)

这是一个演示问题。 更容易让Python处理它:

import sqlite3
conn = sqlite3.connect('/path/to/your.db')
curs = conn.cursor()
results = curs.execute("""SELECT column1 
                            FROM db 
                           WHERE country in ('USA','BRA','CHN') 
                             AND commodity='pork';""").fetchall()
', '.join(str(result[0]) for result in results)

答案 4 :(得分:0)

我相信您正在寻找Table Rotation。我回答了类似的问题here但是我不熟悉SQLLite,所以它可能类似。

答案 5 :(得分:0)

类似的东西:

SELECT column1 as value1 FROM db WHERE country='USA' and commodity='pork'
UNION
SELECT column1 as value2 FROM db WHERE country='BRA' and commodity='pork'
UNION
SELECT column1 as value3 FROM db WHERE country='CHN' and commodity='pork'

答案 6 :(得分:0)

你想要这样的东西:

select 
  base.commodity
,USA_db.column1 as Commodity_USA
,BRA_db.column1 as Commodity_BRA
,CHN_db.column1 as Commodity_CHA
from (select 'pork' as commodity) as base
left join db as USA_db on base.commodity = USA_db.commodity and USA_db.country = 'USA'
left join db as BRA_db on base.commodity = BRA_db.commodity and BRA_db.country = 'BRA'
left join db as CHN_db on base.commodity = CHN_db.commodity and CHN_db.country = 'USA'
;

输出将是:

commodity   Commodity_USA  Commodity_BRA  Commodity_CHA
----------  -------------  -------------  -------------
pork        USA-pork       BRA-pork       USA-pork

答案 7 :(得分:0)

   select max(case country
                 when 'USA' then column1
                 else null
               end) USA,
           max(case country
                 when 'BRA' then column1
                 else null
               end) BRA,
           max(case country
                 when 'CHN' then column1
                 else null
               end) CHN
    FROM db
    WHERE country in ('USA','BRA','CHN')
     and commodity='pork'

对数据进行一次单次传递(单个查询),并汇总三行,换句话说,没有任何内容。

答案 8 :(得分:0)

这应该有效(在mysql中测试)

SELECT GROUP_CONCAT(column1) FROM db WHERE country in ('USA','BRA','CHN') and commodity='pork'

我的测试就是这个(在mysql中)

SELECT GROUP_CONCAT( uid )  FROM pages where title in ('Home','Footer','home')

结果:

1,3,10

这是正确的..