我有下表(仅称为table
):
id name value group_id
PK varchar(32) integer integer
现在,我需要编写一个查询,返回SUM(value)
group_id
分组COUNT(name)
name like '%me%'
group_id
(我不需要计算分组的计数) java.sql.SQLRecoverableException: IO Error: Connection timed out
at oracle.jdbc.driver.T4CConnection.createTemporaryClob(T4CConnection.java:3401)
at oracle.jdbc.driver.PhysicalConnection.createClob(PhysicalConnection.java:9680)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at oracle.ucp.jdbc.proxy.JDBCConnectionProxyFactory.invoke(JDBCConnectionProxyFactory.java:213)
at com.sun.proxy.$Proxy58.createClob(Unknown Source)
at com.ril.payment.PaymentProxyDAO.initiateTransaction(PaymentProxyDAO.java:37)
at com.ril.payment.PaymentProxyFIS.recharge(PaymentProxyFIS.java:153)
at com.ril.payment.PaymentProxyService.recharge(PaymentProxyService.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
,我需要计算满足条件的计数。)
但是,我需要在不编写子查询的情况下这样做,而且我只限于9.2。我倾向于编写一个特定于该需求的自定义聚合函数。这是一个正确的解决方案吗?
答案 0 :(得分:3)
使用9.4,您可以使用过滤后的聚合:
select group_id,
sum(value)
count(name) filter (where name like '%me%')
from the_table
group by group_id;
对于早期版本,您需要使用CASE语句:
select group_id,
sum(value)
count(case when name like '%me%' then 1 end)
from the_table
group by group_id;
这是有效的,因为聚合将忽略空值,如果名称不匹配,case
语句将返回NULL
答案 1 :(得分:2)
应该注意的是,可以通过将bool转换为int来替换大小写的int(disabled
可以替换为LIKE
但更短且更不可读)。
~~
答案 2 :(得分:1)
使用条件聚合
SELECT GROUP_ID,
SUM(VALUE) as SUM_VALUE
SUM(CASE WHEN NAME LIKE '%ME%' THEN 1 ELSE 0 END) as COUNT_VALUE
FROM
TABLE
GROUP BY
GROUP_ID;
另请参阅CASE表达式如何方便https://exploresql.com/2015/08/18/multipurpose-case-expression/