是否可以为case语句提供2个聚合函数 我需要为客户的不同标志获取数量和销售量
基本查询:
Select count(distinct invoices), sum(tot_sal_amt) from stores
尝试:
Select date,case count(invoices)
when (sum(case when custom_flag='guest' then tot_sal_amt end)then count(invoices) end
when (sum(case when custom_flag='non-guest' then tot_sal_amt end)then count(invoices) end
when (sum(case when custom_flag is null then tot_sal_amt end)then count(invoices) end
from stores
任何帮助表示赞赏。
谢谢
答案 0 :(得分:0)
如果可以使用以下格式,则可以:
select date,
custom_flag,
(case
when sum(case when custom_flag='guest' then tot_sal_amt end) then count(distinct invoices)
when sum(case when custom_flag='non-guest' then tot_sal_amt end) then count(distinct invoices)
when sum(case when custom_flag is null then tot_sal_amt end) then count(distinct invoices)
end) as cnt_invoices,
(case
when custom_flag='guest' then sum(tot_sal_amt)
when custom_flag='non-guest' then sum(tot_sal_amt)
when custom_flag is null then sum(tot_sal_amt)
end) as sum_tot_sal_amt
from stores
group by date, custom_flag;
问题发生于
case count(invoices) when
其中
count(invoices)
应该被删除。sum
语句前面的多余的左括号。 但是您无需为您的情况使用case..when
语句,因为在所有情况下结果都是相等的,因此使用以下命令就足够了:< / p>
select date,
custom_flag,
count(distinct invoices) as cnt_invoices,
sum(tot_sal_amt) as sum_tot_sal_amt
from stores
group by date, custom_flag;
答案 1 :(得分:0)
在同一case
语句中可以有两个或多个聚合函数,但不能返回多个值。
未测试伪代码。
Select date
,Count(distinct invoices)
,Count(Case when custom_flag='guest' then invoices
when custom_flag='non-guest' then invoices
when custom_flag is null then invoices end) as cnt_invoices
,Sum(Case when custom_flag='guest' then tot_sal_amt
when custom_flag='non-guest' then tot_sal_amt
when custom_flag is null then tot_sal_amt end) as sum_sal_amt
from stores
group by date
答案 2 :(得分:0)
我很确定您想要条件聚合:
Select date,
count(distinct invoiceid) as num_invoices,
count(distinct case when custom_flag = 'guest' then invoiceid end) as guest_invoices,
count(distinct case when custom_flag = 'non-guest' then invoiceid end) as nonguest_invoices,
count(distinct case when custom_flag is null then invoiceid end) as null_invoices,
sum(total_sal_amt) as total_sales,
sum(case when custom_flag = 'guest' then total_sal_amt end) as guest_total_sal_amt,
sum(case when custom_flag = 'non-guest' then total_sal_amt end) as nonguest_total_sal_amt,
sum(case when custom_flag is null then total_sal_amt end) as null_total_sal_amt
from stores
group by date;
或更简单地说:
Select date, custom_flag,
count(distinct invoiceid) as num_invoices,
sum(total_sal_amt) as total_sales,
from stores
group by date, custom_flag;