在SQL中对查询和子查询项进行分组

时间:2015-11-09 20:18:15

标签: sql group-by subquery

我正在尝试对查询进行分组,以便我的结果只针对每个帐号显示一次。下面是我正在使用的sql。

`select top 10 c.svc, sum(c.tx_amt) as "Total Payments", d.fyear_name, d.fmonth_name, c.acctnbr_int,
(select iif(datediff("d",c.svc_dte,c.pst_dte)<=6 and c.trans_cd in ('0092001','0092051','0093201','0093204','0093212','0093601','0093652','0093653','0093654','0093655','0093701','0096316','0096351','0096366',
'0096405','0096407','0096408','0096409','0096422','0096452','0096455','0096456','0096459','0096473','0096474','0091551'),sum(c.tx_amt),0)) as "POS Payments"
from rptg.vwall_chg_tx_plus c
join rptg.vwdim_date d on c.pst_dte = d.day_date
where c.Pst_Dte > '09/30/2015' and c.Pst_Dte < '11/1/2015'
and c.Svc = '002'
and c.pt_acct_ctg_nme <> 'inpatient'
and c.trans_cd in ('0093101','0093102','0093151','0093152','0093251','0096302','0096303','0096304','0096305','0096306','0096307','0096308','0096309','0096311','0096312',
'0096313','0096314','0096322','0096343','0096352','0096353','0096354','0096355','0096356','0096357','0096358','0096359','0096361','0096362','0096363','0096364','0096367',
'0096372','0096375','0096380','0096381','0096382','0096383','0096392','0096398','0096399','0096426','0096454','0096458','0096477','0096478','0098353','0098354','0098400',
'0098401','0092001','0092051','0093201','0093204','0093212','0093601','0093652','0093653','0093654','0093655','0093701','0096316','0096351','0096366','0096405','0096407',
'0096408','0096409','0096422','0096452','0096455','0096456','0096459','0096473','0096474','0091551','0093254','0093272','0093751','0096395','0096406','0096410','0096412',
'0096413','0096451','0096457','0096472','0099201')
and c.AcctNbr_int in ('3215385349')`

结果是: svc总付款额fyear_name fmonth_name acctnbr_int POS付款 002-150.00 2016财年2016财年M4 3215385349 -150.00 002 -100.00 2016财年FY16 M4 3215385349 -100.00

但结果应该是: Svc POS Pmts总计Pmts FYear_name fmonth_name AcctNbr_int Insrnc_Pyr_Cde 002($ 250.00)($ 250.00)2016财年FY16 M4 3215385349自付

当我尝试对项目和sum(c.tx_amt)进行分组时,我收到有关group by子句中不允许的聚合或子查询的错误消息。

谢谢

1 个答案:

答案 0 :(得分:0)

我能够弄清楚。向子查询添加总和为我提供了所需的结果。

(选择 总和 (iif(datediff(&#34; d&#34;,c.svc_dte,c.pst_dte)&lt; = 6和c.trans_cd在(&#39; 0092001&#39;,&#39; 0092051&#39;,&#39; 0093201&#39;&#39; 0093204&#39;,&#39; 0093212&#39;,&#39; ; 0093601&#39;&#39; 0093652&#39;&#39; 0093653&#39;&#39; 0093654&#39;&#39; 0093655&#39;&#39; 0093701&#39; &#39; 0096316&#39;&#39; 0096351&#39;&#39; 0096366&#39 ;, &#39; 0096405&#39;&#39; 0096407&#39;&#39; 0096408&#39;&#39; 0096409&#39;&#39; 0096422&#39;&#39; 0096452& #39;,&#39; 0096455&#39;&#39; 0096456&#39;&#39; 0096459&#39;&#39; 0096473&#39;&#39; 0096474&#39;,& #39; 0091551&#39;),sum(c.tx_amt),0)))&#34; POS Payments&#34;