Question

I have researched StackOverflow for some answer to composing a CASE statement within an SQL query. The following is what I'm attempting:

select
chkdetail_t.check_acct,
chkheader_t.acct_number,
 CASE WHEN chkdetail_t.check_number = chkdetail_t.check_number THEN SUM(chkdetail_t.amount)
 END AS chek_total,
 chkdetail_t.check_number,
 convert(VARCHAR(10),CAST(chkdetail_t.check_date as datetime), 101) AS chk_date,
 chkdetail_t.amount,
 chkdetail_t.vend_name,
 chkdetail_t.chk_status,
 chkdetail_t.reconsiled,
 chkdetail_t.chk_type,
 chkdetail_t.apr_pay_amt,
 chkdetail_t.apr_disc_amt,
  chkdetail_t.apr_adj_amt

When I run the query I get the following error:

Msg 8120, Level 16, State 1, Line 2 Column 'dbo.chkdetail_t.check_acct' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

My whole objective is to take the check numbers that equal themselves and sum up their total since vendor invoices are issued separately and we pay with one check.

I read another thread that had similar issues but the code I kept plugging in and reading the errors and attempting to fix the SQL query was not working.

Any help would be greatly appreciated.

Sincerely, Mark

Was it helpful?

Solution

select
chkdetail_t.check_acct,
chkheader_t.acct_number,
 SUM(CASE WHEN chkdetail_t.check_number = chkdetail_t.check_number THEN chkdetail_t.amount ELSE NULL END)  AS chek_total,
 chkdetail_t.check_number,
 convert(VARCHAR(10),CAST(chkdetail_t.check_date as datetime), 101) AS chk_date,
 chkdetail_t.amount,
 chkdetail_t.vend_name,
 chkdetail_t.chk_status,
 chkdetail_t.reconsiled,
 chkdetail_t.chk_type,
 chkdetail_t.apr_pay_amt,
 chkdetail_t.apr_disc_amt,
  chkdetail_t.apr_adj_amt

All the columns that are in select statement but not in any aggregate function will go in your GROUP BY Clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top