从两个表中选择最大值、最小值
我有两张桌子。不同之处在于,归档是一个表,另一个保存当前记录。这些是记录公司销售额的表格。在这两个字段中,我们都有其他字段:id、名称、销售价格。我需要从两个表中选择给定名称的最高价格和最低价格。我尝试做这样的查询:
select name, max (price_of_sale), min (price_of_sale)
from wapzby
union
select name, max (price_of_sale), min (price_of_sale)
from wpzby
order by name
但是这样的查询给我绘制了两条记录——一条是当前表,一条是归档表。我想立即从两个表中为最小和最大价格选择一个名称。我如何得到这个查询?
I have two tables. Differ in that an archive is a table and the other holds the current record. These are the tables recording sales in the company. In both we have among other fields: id, name, price of sale. I need to select from both tables, the highest and lowest price for a given name. I tried to do with the query:
select name, max (price_of_sale), min (price_of_sale)
from wapzby
union
select name, max (price_of_sale), min (price_of_sale)
from wpzby
order by name
but such an inquiry draws me two records - one of the current table, one table archival. I want to chose a name for the smallest and the largest price immediately from both tables. How do I get this query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有两个选项(符合 MSSql)
注意:UNION ALL 将合并集合而不消除重复项。这是比 UNION 简单得多的行为。
这个在组合集合之前计算出每个表中的最大值和最小值——这样做可能会更高效。
Here's two options (MSSql compliant)
Note: UNION ALL will combine the sets without eliminating duplicates. That's a much simpler behavior than UNION.
This one figures out the max and min from each table before combining the set - it may be more performant to do it this way.
在 SQL Server 中,您可以使用子查询:
In SQL Server you could use a subquery:
这更像你想要的吗?
它未经测试,但应该在一行上返回所有记录,而不需要联合
Is this more like what you want?
It's untested but should return all your records on one row without the need for a union
SELECT (SELECT MAX(value) FROM table1 WHERE trn_type='CSL' andtil='TILL01') as summ, (SELECT MAX(value) FROM table2WHERE trn_type='CSL' andtil='TILL01') as summ_hist
SELECT (SELECT MAX(value) FROM table1 WHERE trn_type='CSL' and till='TILL01') as summ, (SELECT MAX(value) FROM table2WHERE trn_type='CSL' and till='TILL01') as summ_hist