简体   繁体   中英

Adding a max date subquery to a group by clause

I need to add a max transactional date to this report, so I can see the most recent transaction date for a patient who does not fall under the parameters in the query. This report will be going into a crystal report and I plan to put the last date of service date in the group header for each patient. The code below is to get the max date for each patient. I need the results inserted, so it takes the patients who fall under the below report and gives their max date. Regardless of what is entered for a date. Thank you in advance. SQL Server 2005.

select 
patient_id, 
Max(proc_chron) 

from patient_clin_tran pct
group by patient_id

The Code for the transaction

select patient_id,

(select p.case_status from patient p where p.patient_id = btb.patient_id and p.episode_id = (select max(episode_id) from patient p2 where p2.patient_id = p.patient_id)) as 'Status',
(select p.lname +', '+ p.fname from patient p where p.patient_id = btb.patient_id and p.episode_id = (select max(episode_id) from patient p2 where p2.patient_id = p.patient_id)) AS 'client',
Coverage_plan_id, 
(select proc_code from billing_transaction bt where bt.clinical_transaction_no = btb.clinical_transaction_no and bt.coverage_plan_id=btb.coverage_plan_id and bt.coverage_plan_id = btb.coverage_plan_id) as 'Procedure',
proc_chron, 
(select billing_amt from billing_transaction bt where bt.clinical_transaction_no = btb.clinical_transaction_no and bt.coverage_plan_id = btb.coverage_plan_id) as 'Billing Amount',
balance_amount,
(select max (accounting_date) from  billing_ledger bl where bl.clinical_transaction_no = btb.clinical_transaction_no and subtype = 'pa' and bl.coverage_plan_id = 'standard') as 'Last Payment on Trans',
(select max (instrument_date) from payment p where p.patient_id = btb.patient_id and  p.coverage_plan_id = 'standard') as 'Last Payment on Acct',
(select sum(balance_amount) from billing_transaction_balance btb2 where btb2.patient_id=btb.patient_id and btb2.coverage_plan_id=btb.coverage_plan_id and proc_chron <= CONVERT(CHAR(6), DATEADD(year, -1, DATEDIFF(day, 0,GETDATE())), 112) + '01' and btb2.coverage_plan_id   in('standard')) AS 'Balance'

from billing_transaction_balance btb

where proc_chron <= CONVERT(CHAR(6), DATEADD(year, -1, DATEDIFF(day, 0, GETDATE())), 112) + '01' and coverage_plan_id   in('standard') 

group by patient_id, proc_chron, coverage_plan_id, balance_amount, clinical_transaction_no

In your transaction code, you need to add all the Select columns which are not being aggregated to the Group By. I count 8 non-aggregated columns in the Select statement, so you must have all 8 in the Group By.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM