gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:39:48 25 4
gpt4 key购买 nike

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

我使用表(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com