我正在尝试编写一个将带回订单号的查询,除非交易中有多个订单号,这将需要返回单词Multiple。我得到的一个组不能包含聚合,但是如果我把它拿出来就说非聚合值必须是关联组的一部分。有任何想法吗?以下代码是我目前的代码
Select
s.Loc_id as Loc_ID
,lh.loc_nbr as Store_Nbr
,s.sltrn_dt as Sales_date
,s.rgstr_sls_post_dt as Sales_Post_Date
,s.sltrn_id As Trans_ID
,s.sls_tm as Sales_Time
,zeroifnull(HDISS_TAX_EXMPT_ID) as Exempt_ID
,sum(net_ce_sls_amt)
,sum(mkdn_amt)
,sum(tax_amt)
,sum(grs_sls_amt)
,sr.cust_ord_nbr
FROM PR_US_SALES_UNSEC_VIEWS.SLTRN s
join
PR_US_SALES_UNSEC_VIEWS.SLTRN_TAX_EXMPT ste
on (s.loc_id = ste.loc_id and s.sltrn_dt = ste.sltrn_dt and s.pos_rgstr_id = ste.pos_rgstr_id and s.sltrn_id = ste.sltrn_id)
join
pr_shrd_views.loc_hier lh
on(s.loc_id = lh.loc_id)
join pr_us_sales_unsec_views.sltrn_rsm sr
on (s.loc_id = sr.loc_id and s.sltrn_dt = sr.sltrn_dt and s.pos_rgstr_id = sr.pos_rgstr_id and s.sltrn_id = sr.sltrn_id)
where s.sltrn_dt between '2012-07-06' and current_date
--and lh.loc_nbr in (1501, 1523, 1528, 1551)
and trans_typ_cd in (1,3)
and trans_stat_cd = 1
and ipv_flg= 'N'
--HAVING COUNT( cust_ord_nbr ) > 1
Group by 1,2,3,4,5,6,7,12
答案 0 :(得分:1)
当您取消注释HAVING(应该在GROUP BY之后)时,您需要从GROUP BY中删除cust_ord_nbr
并在选择列表中应用聚合函数,例如MIN(cust_ord_nbr)
。
根据你的叙述,你想要这样的东西:
select
...
,sum(grs_sls_amt)
,case
when COUNT(DISTINCT cust_ord_nbr ) > 1
then 'multiple'
else trim(min(sr.cust_ord_nbr)
end
FROM PR_US_SALES_UNSEC_VIEWS.SLTRN s
...
Group by 1,2,3,4,5,6,7
答案 1 :(得分:0)
SELECT Order_Nbr
FROM YourTable
GROUP BY Order_Nbr
HAVING COUNT( cust_ord_nbr ) > 1;