【发布时间】:2011-05-23 22:07:46
【问题描述】:
我经常发现自己在group by 子句中添加了我确信是独一无二的表达式。有时结果证明我错了 - 因为我的 SQL 中的错误或错误的假设,而那个表达式并不是真正唯一的。
在很多情况下,我宁愿这会产生一个 SQL 错误,而不是默默地扩展我的结果集,有时甚至非常巧妙。
我希望能够做类似的事情:
select product_id, unique description from product group by product_id
但显然我自己无法实现 - 但可以在某些数据库上使用用户定义的聚合来实现几乎同样简洁的东西。
只允许一个唯一输入值的特殊聚合通常对所有版本的 SQL 都有帮助吗?如果是这样,现在可以在大多数数据库上实现这样的事情吗? null 值应该像任何其他值一样被考虑 - 与内置聚合 avg 通常工作的方式不同。 (我已经添加了针对 postgres 和 Oracle 的实现方式的答案。)
以下示例旨在说明如何使用聚合,但这是一个简单的情况,其中很明显哪些表达式应该是唯一的。实际使用更有可能是在较大的查询中,这样更容易对唯一性做出错误的假设
表格:
product_id | description
------------+-------------
1 | anvil
2 | brick
3 | clay
4 | door
sale_id | product_id | cost
---------+------------+---------
1 | 1 | £100.00
2 | 1 | £101.00
3 | 1 | £102.00
4 | 2 | £3.00
5 | 2 | £3.00
6 | 2 | £3.00
7 | 3 | £24.00
8 | 3 | £25.00
查询:
> select * from product join sale using (product_id);
product_id | description | sale_id | cost
------------+-------------+---------+---------
1 | anvil | 1 | £100.00
1 | anvil | 2 | £101.00
1 | anvil | 3 | £102.00
2 | brick | 4 | £3.00
2 | brick | 5 | £3.00
2 | brick | 6 | £3.00
3 | clay | 7 | £24.00
3 | clay | 8 | £25.00
> select product_id, description, sum(cost)
from product join sale using (product_id)
group by product_id, description;
product_id | description | sum
------------+-------------+---------
2 | brick | £9.00
1 | anvil | £303.00
3 | clay | £49.00
> select product_id, solo(description), sum(cost)
from product join sale using (product_id)
group by product_id;
product_id | solo | sum
------------+-------+---------
1 | anvil | £303.00
3 | clay | £49.00
2 | brick | £9.00
错误案例:
> select solo(description) from product;
ERROR: This aggregate only allows one unique input
【问题讨论】:
-
你用的是哪个数据库mysql,oracle,mysql有没有solo函数
-
@Rahul 这是一个一般性的 SQL 问题 - 我希望得到我不熟悉的数据库(postgres 和 Oracle)的答案
标签: sql mysql sql-server oracle postgresql