从两张桌子中获取最昂贵,最便宜的物品

时间:2015-03-23 14:03:54

标签: sql sql-server

我正试图从两张不同的桌子上买到最贵,最便宜的物品。 输出应该是一行,其值为MostExpensiveItem,MostExpensivePrice,CheapestItem,CheapestPrice

我能够通过以下查询获得两张表中最昂贵和最便宜的商品的价格:

SELECT
   MAX(ExtrasPrice) as MostExpensivePrice, MIN(ExtrasPrice) as CheapestPrice
FROM
    (
    SELECT ExtrasPrice FROM Extras
    UNION ALL
    SELECT ItemPrice FROM Items
    ) foo

如何将项目名称(ItemName,ExtrasName)添加到输出中?同样,应该只有一行作为输出。

3 个答案:

答案 0 :(得分:1)

带有TOP 1子句的

order by应该适合您。试试这个

SELECT *
FROM   (SELECT TOP 1 ExtrasPrice,ExtrasName
        FROM   Extras ORDER  BY ExtrasPrice Asc),
       (SELECT TOP 1 ItemPrice,ItemName
        FROM   Items ORDER  BY ItemPrice Desc) 

注意: Comma可以替换为CROSS JOIN

答案 1 :(得分:1)

试试这个:

SELECT TOP 1 FIRST_VALUE(Price) OVER (ORDER BY Price) AS MinPrice,
           FIRST_VALUE(Name) OVER (ORDER BY Price) AS MinName,
           LAST_VALUE(Price) OVER (ORDER BY Price DESC) AS MaxPrice,
           LAST_VALUE(Name) OVER (ORDER BY Price DESC) AS MaxName
    FROM (
        SELECT ExtrasName AS Name, ExtrasPrice AS Price FROM Extras
        UNION ALL
        SELECT ItemName As Name, ItemPrice AS Price FROM Items) u

SQL Fiddle Demo

答案 2 :(得分:0)

您可以使用row_number()。如果您对两行感到满意:

SELECT item, price
FROM (SELECT foo.*, row_number() over (order by price) as seqnum_asc,
             row_number() over (order by price) as seqnum_desc
      FROM (SELECT item, ExtrasPrice as price FROM Extras
            UNION ALL
            SELECT item, ItemPrice FROM Items
           ) foo
     ) t
WHERE seqnum_asc = 1 or seqnum_desc = 1;

编辑:

如果两个表中的“价格”都有索引,那么最便宜的方法可能是:

with exp as (
     (select top 1 item, ExtrasPrice as price
       from Extras e
       order by price desc
     ) union all
     (select top 1 i.item, ItemPrice
      from Items i
      order by price desc
     )
    ),
    cheap as (
     (select top 1 item, ExtrasPrice as price
       from Extras e
       order by price asc
     ) union all
     (select top 1 i.item, ItemPrice
      from Items i
      order by price asc
     )
    )
select top 1 *
from exp
order by price desc
union all
select top 1 *
from cheap
order by price asc;  

如果您希望将其放在一行中,则可以使用以下命令替换最终查询:

select e.*, c.*
from (select top 1 *
      from exp
      order by price desc
     ) e cross join
    (select top 1 *
     from cheap
     order by price asc
    ) c