从特定列的两个表中获取最佳行

时间:2016-03-31 09:44:59

标签: sql sql-server sql-server-2008 join

我有两张表来自两家价格不同的公司几乎相同的数据。

我想从价格低廉的任何一个表中选择一行。

如何比较行并从两个表中获取最佳值

我已经将查询编写为此,但价格部分存在歧义。

select min(Price), Brand, a.Color 
from [table1] a, table2 b 
where a.BrandName = b.BrandName and a.Shape like b.Shape 
      and (a.color = b.color or a.Color is null)

我的价格出现歧义错误。我该如何解决它。

2 个答案:

答案 0 :(得分:1)

如果您想使用UNION

,可以使用MIN执行此操作
SELECT min(price),brand,max(color)
FROM (select price,brand,color FROM table1
      UNION
      select price,brand,'' FROM table2)
GROUP BY brand

或者您可以将CASE EXPRESSION与联接使用:

select CASE WHEN a.price > b.price then b.price else a.price end as min_price
       ,a.Brand
       ,a.Color
from table1 a
INNER JOIN  table2 b
ON a.BrandName=b.BrandName
WHERE and a.Shape like b.Shape and (a.color=b.color or  a.Color is null)

答案 1 :(得分:0)

你可以试试这个:

 select 
    case when min(a.price)<min(b.price) then min(a.price) else min(b.price) end as     min_price, 
    Brand,a.Color from [table1] a, table2 b where a.BrandName=b.BrandName and a.Shape = b.Shape and a.color=b.color
group by Brand,a.color
    UNION 
    select 
    case when min(a.price)<min(b.price) then min(a.price) else min(b.price) end as     min_price, 
    Brand,a.Color from [table1] a, table2 b where a.BrandName=b.BrandName and a.Shape = b.Shape and  a.Color is null
group by Brand,a.color