从查询中显示不同的行记录

时间:2015-02-19 06:32:32

标签: sql sql-server database sql-server-2008-r2

我有两张桌子:

产品:

enter image description here

图片:

enter image description here

我在查询中通过idProduct加入这些表。

我已经形成了一些必要条件的查询:

select p.prdColor prdColor, p.sku,I.Image,p.descriptselect p.prdColor
prdColor, p.sku,I.Image,p.description,ISNULL(price,0) price from     
products p,Images I       where p.idProduct=i.idproduct       and
p.PrdParentSku=(select PrdParentSku from products where
sku='120PBOOTCAT12') and      I.DisplayOrder=1                and
isnull(p.prdColor,'')!=''  

它给了我结果:

enter image description here

现在,我想通过不同的prdColor

获取记录

表示prd颜色应该只是cat和dinosor(上面只有两个记录)

如何编写查询???

我试过了:

select distinct p.prdColor prdColor, p.sku,I.Image,p.description,ISNULL(price,0) price from 
      products p,Images I 
      where p.idProduct=i.idproduct 
      and p.PrdParentSku=(select PrdParentSku from products where sku='120PBOOTCAT12') and 
      I.DisplayOrder=1           
      and isnull(p.prdColor,'')!='' 
      group by p.sku,I.Image,p.description,ISNULL(price,0),p.prdColor

但这并没有帮助。

请帮帮我。

预期:

prdColor   SKU            Image           Description 

cat         whatever      whatever         whatever

dianosor    whatever      whatever         whatever

注意: - 无论是prdcolor的前1条记录

2 个答案:

答案 0 :(得分:2)

尝试使用ROW_NUMBER()

SELECT * FROM 
(
    select p.prdColor prdColor, p.sku,
          I.Image,p.descriptselect p.prdColor
          prdColor, p.sku,I.Image,
          p.description,ISNULL(price,0) price,
          ROW_NUMBER() OVER(partition by p.prdColor order by p.prdColor) RowNum
     from products p,Images I       
     where p.idProduct=i.idproduct and
             p.PrdParentSku=(select PrdParentSku from products where
             sku='120PBOOTCAT12') and I.DisplayOrder=1   and
             isnull(p.prdColor,'')!='' 
) AS A
WHERE A.RowNum = 1

答案 1 :(得分:1)

您需要使用加入

select p.prdColor prdColor, p.sku,I.Image,p.descriptselect p.prdColor prdColor, p.sku,I.Image,p.description,ISNULL(price,0) price from products p inner join Images I ON p.idProduct=i.idproduct  AND p.PrdParentSku=(select PrdParentSku from products where sku='120PBOOTCAT12') and      I.DisplayOrder=1                and isnull(p.prdColor,'')!=''
像这样