如果特定列具有值[重复],请选择多行

问题描述 投票:0回答:2

这个问题在这里已有答案:

我有这样的表(简化):

表名:产品

productId, property, value
----------------------------
1, color, red
1, shape, square
1, price, 1.00
...
2, color, green
2, shape, triangle
2, price, 0.50
...
10, color, red
10, shape, circle
10, price, 3.00
...

我简化了它,但我希望它有意义。对于一个特定的数据集,我有多行,在这种情况下是产品。每行描述产品的不同属性。

我现在想要选择具有特殊属性的所有产品,让我们说所有color都是red的产品。但不仅是颜色为红色的行,而是colorred的每个产品的每一行。

对不起,这个描述非常糟糕,但我希望你知道我的意思。鉴于上面的表结构,如果我想选择所有红色产品,我想最终得到这样的结果:

productId, color, shape, price
-------------------------------
1, red, square, 1.00
10, red, circle, 3.00

这有意义吗?也许有人可以帮忙。

顺便说一下:我无法改变给定的表结构。它来自外部应用程序。

sql firebird fastreport
2个回答
2
投票

一种方法使用exists

select p.*
from products p
where exists (select 1
              from products p2
              where p2.productId = p.productId and
                    p2.property = 'color' and p2.value = 'red
             );

如果你想要这一行,那么你可以使用条件聚合来总结:

select p.productid,
       max(case when p.property = 'color' then p.value end) as color,
       max(case when p.property = 'shape' then p.value end) as shape,
       max(case when p.property = 'price' then p.value end) as price
from products p
group by productId
having max(case when p.property = 'color' then p.value end) = 'red';

0
投票

看一下pivot命令。这是我发现将行转换为列的最佳方式,前提是列是静态的。如果它们不是可以通过动态sql实现它,但有点复杂。我使用该方法为产品属性构建视图,这听起来与您在此处所做的非常相似。

© www.soinside.com 2019 - 2024. All rights reserved.