SQL不确定如何使用select count作为子查询?
表t1:SQL不确定如何使用select count作为子查询?,sql,sql-server,Sql,Sql Server,表t1: columns: id location calendar schdate schtype select t1.id, t1.location, t1.calendar, min(t1.schdate), max(t1.schdate) from table t1 group by t1.id, t1.location, t1.calendar 上述选择将产生以下结果: 123 1 Base 8/7/2018 8/18/2018 123 1
columns:
id
location
calendar
schdate
schtype
select t1.id, t1.location, t1.calendar, min(t1.schdate), max(t1.schdate)
from table t1
group by t1.id, t1.location, t1.calendar
上述选择将产生以下结果:
123 1 Base 8/7/2018 8/18/2018
123 1 Add 8/14/2018 8/17/2018
234 1 Base 8/8/2018 8/31/2018
234 1 Add 8/24/2018 8/24/2018
我现在尝试添加另外两列结果,它们是基于schstyle的计数,其中上面的其他因素保持不变
差不多
select t1.id, t1.location, t1.calendar, min(t1.schdate), max(t1.schdate),
(select count(t1.schdate) from table t1 where schtype=1),
(select count(t1.schdate) from table t1 where schtype=2)
from table t1
group by t1.id, t1.location, t1.calendar
谢谢我想您正在寻找条件聚合。另外,在您的示例中,您缺少了
分组依据
(假设,因为这只是一个示例?)。无论哪种方式,这样的方法都应该有效:
select t1.id, t1.location, t1.calendar, min(t1.schdate), max(t1.schdate),
sum(case when schtype=1 then 1 else 0 end) as schtype1,
sum(case when schtype=2 then 1 else 0 end) as schtype2
from table t1
group by t1.id, t1.location, t1.calendar
如果我理解正确,您可以尝试使用条件聚合函数而不是子查询
select
t1.id,
t1.location,
t1.calendar,
min(t1.schdate),
max(t1.schdate),
sum(CASE WHEN schtype=1 THEN 1 END),
sum(CASE WHEN schtype=2 THEN 1 END)
from table t1
GROUP BY
t1.id,
t1.location,
t1.calendar
您能提供一些示例数据和预期结果吗?您的第一个查询将不会生成该结果集。您将得到一个语法错误。实际上有多个错误。
id
列应该是主键,因此查询只会复制表Min
和Max
的值将是相同的(=schdate
),您不必使用函数,也不必使用分组方式
。对于这两个新列,您当然可以使用条件表达式之类的东西,或者只使用2-schtype
和schtype-1
之类的表达式。这看起来是FILTER
子句的完美例子,但它很少实现。@impler不是只有postgres
才支持吗?是的,可惜没有得到更广泛的支持。。。