sql - 从 SQLite 中的两行生成结果表中的一行

标签 sql sqlite

标题已更改!问题是将行合并到列。

我使用表(ImageAttribute)在数据库中标记图像(表图像),该表基本上有两行 - 一行用于属性类型,另一行用于值。

数据库是:

Image.id
Image.URI
ImageAttribute.imageId
ImageAttribute.attributeType
ImageAttribute.attributeValue     

ImageAttribute.imageId指的是Image.id

一张图像可能有许多属性。例如:

imageId | attributeType | attributeValue
--------+---------------+---------------
1       |COLOR          | blue
1       |QUALITY        | good
1       |MEMO           | some notes for image 1
2       |COLOR          | red
2       |QUALITY        | good
2       |OBJECTS        | cars, trees

不同图像的属性集可能有所不同。

是否可以选择具有任意值的属性 COLOR 且 QUALITY='good' 的所有图像,并将此信息显示在一行中,例如:

id      | COLOR         | QUALITY        
--------+---------------+---------------
1       |blue           | good
2       |red            | good

最佳答案

一种选择是使用条件聚合来基本上透视您的结果:

select imageid, 
       max(case when attributetype = 'color' then attributevalue end) Color,
       max(case when attributetype = 'quality' then attributevalue end) Quality
from imageattribute
group by imageid

如果您需要仅过滤 quality = good 的结果,那么您可以添加 having 语句:

having max(case when attributetype = 'quality' then attributevalue end) = 'good'

关于sql - 从 SQLite 中的两行生成结果表中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28743022/

相关文章:

python - 将字符串列表绑定(bind)到 IN 子句

安卓 SQLite : nullColumnHack parameter in insert/replace methods

ios - 如何将文件从主包复制到文档文件夹

sql - 为什么 json_populate_record() 无法识别行类型?

sql - PostgreSQL 转换错误

mysql - 与其他行的连接获得相同的结果

java - 严重 : null java. sql.SQLException

sql - Oracle Sql获取另一列的每个不同值出现次数最多的值

SSIS foreach 循环中的 SQL 任务 - 达到最大池大小错误

java - SQLite 查询读取错误的 Id