Sql server 使用distinct where子句向我的查询中添加另一列
有没有一种方法可以向第一个查询中添加另一个列,其中有一个单独的where子句不应用于其他列Sql server 使用distinct where子句向我的查询中添加另一列,sql-server,Sql Server,有没有一种方法可以向第一个查询中添加另一个列,其中有一个单独的where子句不应用于其他列 select month(From_iso8601_timestamp(u.created)) as Month, count(distinct u.id) as Sign_Ups, count (distinct w.owner) as Sign_Ups_with_Want_Created, count(distinct g.owner) as Sign_Ups_with_Reel_Cr
select
month(From_iso8601_timestamp(u.created)) as Month,
count(distinct u.id) as Sign_Ups,
count (distinct w.owner) as Sign_Ups_with_Want_Created,
count(distinct g.owner) as Sign_Ups_with_Reel_Created
from
prodjoinreel.users u
left join prodjoinreel.goals g on g.owner = u.id
left join prodjoinreel.wants w on w.owner = u.id
where year(From_iso8601_timestamp(u.created)) = 2019
group by 1
order by 1
查询我想添加的附加列(我只想将where g.status='done'应用于Sign\u ups\u with\u complete\u revel列):
谢谢如果我理解正确,那么您应该将“g.status=”done“从覆盖整个查询的where语句移动到count聚合中的case语句中。我已经在下面完成了这项工作,我还对您的查询进行了一些修改,以避免在月份计算中出现冗余:
select New_Users = count(distinct u.id),
ap.Month,
Sign_Ups_with_Want_Created = count(distinct w.owner),
Sign_Ups_with_Reel_Created =
count(distinct
case
when g.status = 'done' then g.owner
end
)
from prodjoinreel.goals g
right join prodjoinreel.users u on g.owner = u.id
cross apply (select Month = From_iso8601_timestamp(u.created)) ap
where year(From_iso8601_timestamp(u.created)) = 2019
group by ap.Month
order by ap.Month
按2分组
?为什么要按整数2分组?也不能按顺序位置分组。必须使用列的表达式。因此,在本例中,它将是“按月分组(从_iso8601_timestamp(u.created))”,我同意@Larnu的观点,即您不应该按顺序进行订购。这充其量是有问题的。
select New_Users = count(distinct u.id),
ap.Month,
Sign_Ups_with_Want_Created = count(distinct w.owner),
Sign_Ups_with_Reel_Created =
count(distinct
case
when g.status = 'done' then g.owner
end
)
from prodjoinreel.goals g
right join prodjoinreel.users u on g.owner = u.id
cross apply (select Month = From_iso8601_timestamp(u.created)) ap
where year(From_iso8601_timestamp(u.created)) = 2019
group by ap.Month
order by ap.Month