如何获得使用SQL应用的交替函数的列?

如何获得使用SQL应用的交替函数的列?,sql,Sql,示例数据: Fruit Price Apple 1 Apple 4 Apple 5 Orange 3 Orange 7 Orange 10 Pear 2 Pear 7 水果价格 苹果1 苹果4 苹果5 橙色3 橙色7 橙色10 梨2 梨7 我想使用SQL获取此表: Fruit Price Apple

示例数据:

Fruit Price Apple 1 Apple 4 Apple 5 Orange 3 Orange 7 Orange 10 Pear 2 Pear 7 水果价格 苹果1 苹果4 苹果5 橙色3 橙色7 橙色10 梨2 梨7 我想使用SQL获取此表:

Fruit Price Apple 1 Apple 5 Orange 3 Orange 10 Pear 2 Pear 7 水果价格 苹果1 苹果5 橙色3 橙色10 梨2 梨7 所以基本上我想要每个水果有两个记录,最小价格和最大价格。我正在与SAP HANA合作

使用这样的工会:

小提琴:

如果某些水果只有一个价格,请使用UNION而不是UNION ALL,这将消除重复:

select fruit, min(price) as price
from table_name
group by fruit
union
select fruit, max(price)
from table_name
group by fruit
order by fruit, price

下面的代码将执行您想要的操作,并将示例数据用作测试

使用临时表

create table #fruits
(
  idFruit int identity (1,1) not null,
  Fruit varchar(25) default null,
  Price decimal default null,
  guidFruit uniqueidentifier default newsequentialid(),
  dtCreate datetime default getutcdate()
)
使用SQL 2008R2+one语句插入

INSERT into #fruits (Fruit, Price)
VALUES
  ('Apple', 1),
  ('Apple', 4),
  ('Apple', 5),
  ('Orange', 3),
  ('Orange', 7),
  ('Orange', 10),
  ('Pear',   2),
  ('Pear',   7);
显示表中的所有数据

select * from #fruits;
现在只使用最小/最大值构建输出查询 是的,我们可以用CTE构建它,但他们可能没有那个功能

select
 mm.Fruit,
 mm.Price
from
(
  select
   f.Fruit,
   min(f.Price) as [Price]
  from
    #fruits f
  group by 
    f.fruit
  union all
  select
   f.Fruit,
   max(f.Price) as [Price]
  from
    #fruits f
  group by 
    f.fruit
) as mm
order by
 mm.Fruit asc,
 mm.Price asc;

我真的不明白你想说什么。你想做张桌子吗?或者您正在尝试查询表?请澄清你有什么以及你想要更好一点的。我想查询第一个表,得到一个看起来像第二个表的表。这很完美,谢谢
select
 mm.Fruit,
 mm.Price
from
(
  select
   f.Fruit,
   min(f.Price) as [Price]
  from
    #fruits f
  group by 
    f.fruit
  union all
  select
   f.Fruit,
   max(f.Price) as [Price]
  from
    #fruits f
  group by 
    f.fruit
) as mm
order by
 mm.Fruit asc,
 mm.Price asc;