Not a single-group group function while using case when statements - sql

In a query I am trying to use case when keywords. I have to check for 3 conditions there. But I am getting Not a single-group group function error. Any syntax error in my query? Please guide.
Query is
SELECT
CASE WHEN DIST_TYPE_ID IN (5033,5034,5035,5036)
THEN MIN (b2b_start_dt +NVL(access_lead_Days,0))
ELSE
CASE WHEN MAX(overridden) = 0
THEN NVL (MIN (src_start_dt), MIN (b2b_start_dt))
ELSE MAX(B2B_START_dT) END
END as start_date
FROM prog_access_movie_v
WHERE trunc(SYSDATE) BETWEEN b2b_start_dt AND b2b_end_dt
AND (user_id IS NOT NULL OR GROUP_ID IS NOT NULL)
AND dist_type_id IN (5034) AND prog_id = (432899)

This is the select:
SELECT (CASE WHEN DIST_TYPE_ID IN (5033, 5034, 5035, 5036)
THEN MIN(b2b_start_dt + NVL(access_lead_Days, 0))
ELSE (CASE WHEN MAX(overridden) = 0
THEN NVL(MIN(src_start_dt), MIN(b2b_start_dt))
ELSE MAX(B2B_START_dT)
END)
END) as start_date
In terms of aggregation, everything is fine except for the condition on DIST_TYPE_ID. If you had:
SELECT (CASE WHEN MAX(DIST_TYPE_ID) IN (5033, 5034, 5035, 5036)
THEN MIN(b2b_start_dt + NVL(access_lead_Days, 0))
ELSE (CASE WHEN MAX(overridden) = 0
THEN NVL(MIN(src_start_dt), MIN(b2b_start_dt))
ELSE MAX(B2B_START_dT)
END)
END) as start_date
Or:
SELECT (CASE WHEN SUM(CASE WHEN DIST_TYPE_ID IN (5033, 5034, 5035, 5036) THEN 1 ELSE 0 END) > 0
THEN MIN(b2b_start_dt + NVL(access_lead_Days, 0))
ELSE (CASE WHEN MAX(overridden) = 0
THEN NVL(MIN(src_start_dt), MIN(b2b_start_dt))
ELSE MAX(B2B_START_dT)
END)
END) as start_date
Or a myriad of other possibilities, then the query should parse and execute.

It was a silly mistake from me . Group by dist_type_id worked out.
SELECT CASE WHEN DIST_TYPE_ID IN (5033,5034,5035,5036) THEN MIN (b2b_start_dt +NVL(access_lead_Days,0))
ELSE CASE WHEN MAX(overridden) = 0 THEN NVL (MIN (src_start_dt), MIN (b2b_start_dt)) ELSE MAX(B2B_START_dT) END END as start_date
FROM prog_access_movie_v
WHERE trunc(SYSDATE) BETWEEN b2b_start_dt AND b2b_end_dt
AND (user_id IS NOT NULL OR GROUP_ID IS NOT NULL)
AND dist_type_id IN (5034) AND prog_id = (432899)
group by access_lead_days, dist_type_id

Related

SQL CASE WHEN THEN logics of calculating the types of a column

Have a tableA like this:
I wanna receive a tableŠ˜ like this (group by startTime and endTime, count of Severity in cnt column and count of every type of Severity in a distinct column):
The simple count (cnt column) works fine. But with the other I tired CASE WHEN THEN logics and it seems not working (line 10 for example). Can you please assist me with SQL query in this case.
You need conditional aggregation :
select starttime, endtime, count(*),
sum(case when severity = 'low' then 1 else 0 end),
sum(case when severity = 'med' then 1 else 0 end),
sum(case when severity = 'high' then 1 else 0 end)
from table t
group by starttime, endtime;
Try below query: with case when
select starttime, endtime, count(severity) as cnt, count(case when severity='LOW' then 1 end) cnt_low,count(case when severity='MED' then 1 end) cnt_med,count(case when severity='HIGH' then 1 end) as cnt_high
from tablename
group by starttime, endtime
use case when and aggregate function sum
select startTime , endTime,count(*) as Cnt,
sum( case when Severity='MED' then 1 else 0 end) as cntMed,
sum( case when Severity='LOW' then 1 else 0 end) as cntLow,
sum( case when Severity='HIGH' then 1 else 0 end) as cntHIGH from yourtable
group by startTime , endTime

Why doesn't the "having" clause work?

For the following query:
select count(distinct email_address)
from
(
select distinct email_address,
case when elq_activity_type='EmailSend' then 1 else 0 end 'Sends',
case when elq_activity_type='Bounceback' then 1 else 0 end 'Bounces',
case when elq_activity_type='EmailOpen' then 1 else 0 end 'Opens',
case when elq_activity_type='EmailClickthrough' then 1 else 0 end 'Clicks'
from elq_stg_activity
) a
having sum(sends-bounces)>0
The having clause doesn't seem to be doing anything. What am I doing wrong?
Need to get all unique emails that had an email delivered to them (send-bounce).
Thanks!
I think you want this:
select count(email_address)
from (select email_address,
sum(case when elq_activity_type = 'EmailSend' then 1 else 0 end) Sends,
sum(case when elq_activity_type = 'Bounceback' then 1 else 0 end) as Bounces,
sum(case when elq_activity_type = 'EmailOpen' then 1 else 0 end) as Opens,
sum(case when elq_activity_type = 'EmailClickthrough' then 1 else 0 end) as Clicks
from elq_stg_activity
group by email_address
) a
where sends = bounces;
There are numerous issues with your query. This is the only sensible interpretation I could think of.

Update a complex SQL query to add a new column with the sum of two columns

The below SQL query creates a table with n number of columns named in the next line.
...., curr_amount, tax_amount, ....
I am having a very tough time updating the below query to create a new column called total and position it exactly after tax_amount column and the total column should contain the values that are obtained after sum of curr_amount & tax_amount.
I have been working on this from more than one day but couldn't figure it out.
P.S. Still a noob here. Thanks alot for your time.
.
SELECT Isnull(t.total_month, 'Total') total_month,
t.tax_amount,
t.curr_amount,
t.usage_qty,
t.kh_qty,
t.bill_cnt
FROM (SELECT dbo.Sigmadf(bm.posted_date, 'YYYY-MM') total_month,
Sum(CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END) usage_qty,
Sum(CASE
WHEN bm.curr_amount IS NULL THEN 0
ELSE bm.curr_amount
END) curr_amount,
Sum(CASE
WHEN bm.adj_amount IS NULL THEN 0
ELSE bm.adj_amount
END) adj_amount,
Sum(CASE
WHEN bm.bal_fwd_amount IS NULL THEN 0
ELSE bm.bal_fwd_amount
END) bal_forward,
Sum(CASE
WHEN bm.tax_amount IS NULL THEN 0
ELSE bm.tax_amount
END) tax_amount,
Sum(CASE
WHEN bm.due_amount IS NULL THEN 0
ELSE bm.due_amount
END) due_amount,
Sum(CASE
WHEN bm.last_total_paid_amount IS NULL THEN 0
ELSE bm.last_total_paid_amount * -1
END) paid_amount,
Sum(CASE
WHEN bm.bill_print = 'Y' THEN 1
ELSE 0
END) pdf_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '0' THEN 1
ELSE 0
END) reg_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '1' THEN 1
ELSE 0
END) ftime_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '9999' THEN 1
ELSE 0
END) ltime_cnt,
Count(*) bill_cnt,
Sum(CASE
WHEN bill_status = '01' THEN 1
ELSE 0
END) canc_cnt,
Sum(CASE
WHEN bill_status = '01' THEN
CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END
ELSE 0
END) canc_usg,
Sum(CASE
WHEN vis.kh_qty IS NULL THEN 0
ELSE Cast(vis.kh_qty AS NUMERIC(18, 2))
END) kh_qty
FROM bill_master bm WITH (nolock)
INNER JOIN (SELECT bill_no,
Sum(CASE
WHEN vpb.recurr_charge_type IN ( 'T4',
'SLF' )
THEN
CASE
WHEN vpb.print_qty = 'Y'
AND vpb.usage_qty IS NOT NULL
THEN
Cast (vpb.usage_qty AS
NUMERIC(18, 2))
ELSE 0
END
ELSE 0
END) usage_qty
FROM v_print_bills_all vpb
GROUP BY bill_no) rr
ON rr.bill_no = bm.bill_no
LEFT OUTER JOIN vis_bill_master_cr vis WITH (nolock)
ON bm.bill_no = vis.bill_no
WHERE 1 = 1
AND dbo.Trunc(bm.posted_date) >= '20150101'
AND dbo.Trunc(bm.posted_date) <= '20151124'
AND bm.posted_date IS NOT NULL
AND bm.cust_id NOT IN (SELECT cc.code_type cust_id
FROM code_table cc WITH (nolock)
WHERE cc.code_tabname = 'RptExclCust'
AND cc.code_value = 'cust_id')
GROUP BY dbo.Sigmadf(bm.posted_date, 'YYYY-MM') WITH rollup)t
I must say that the explanation is not so clear.
From my understanding, you want the total of two columns.
So, wrap all your query between parenthesis, call it subQuery, and make the sum of the two columns on top:
SELECT subQuery.total_month as bill_date,
subQuery.curr_amount as amount,
subQuery.tax_amount tax,
subQuery.curr_amount + subQuery.tax_amount as [total],
...
FROM
(..your entire query here..) as subQuery

Select with subquery select not working

I keep getting that error on this code. I am not using EXISTS.Please Help.
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
SQL:
If ISDATE(#grpsearch) = 1
SELECT grp.GroupID,
vlanlist.InternetType,
grp.GroupName, cast(grp.StartDateTime as date) as StartDate,
convert(varchar,cast(grp.StartDateTime as time),100) as starttime,
(select case when datepart(hh,convert(datetime,grp.StartDateTime)) > 12 then datepart(hh,convert(datetime,grp.StartDateTime))-12
else case when datepart(hh,convert(datetime,grp.StartDateTime)) = 0 then '12' else datepart(hh,convert(datetime,grp.StartDateTime)) end end as starthour,
datepart(mi,convert(datetime,grp.StartDateTime)) as startmin, case when datepart(hh,convert(datetime,grp.StartDateTime)) >= 12 then 'PM' else 'AM' end as startperiod),
cast(grp.enddatetime as date) as EndDate,
convert(varchar,cast(grp.EndDateTime as time),100) as EndTime,
grp.UserInitials,
grp.UserComments,
roomlist.RoomName,
jacklist.JackNumber
FROM a_Cisco.dbo.grp_internet as grp left outer join
dbo.jacklist as jacklist ON grp.intJack = jacklist.intJack left outer join
dbo.roomlist as roomlist ON grp.intRoom = roomlist.intROom left outer join
dbo.vlanlist as vlanlist ON grp.VlanID = vlanlist.VlanID
WHERE (convert(varchar,cast(grp.StartDateTime as date),100) = #grpsearch)
The problem is this part of the query:
(select case when datepart(hh,convert(datetime,grp.StartDateTime)) > 12
then datepart(hh,convert(datetime,grp.StartDateTime))-12
else case when datepart(hh,convert(datetime,grp.StartDateTime)) = 0
then '12' else datepart(hh,convert(datetime,grp.StartDateTime))
end
end as starthour,
First, you don't need the select at all. Second, you are missing the closing parentheses ()). I would suggest:
(case when datepart(hh,convert(datetime,grp.StartDateTime)) > 12
then datepart(hh,convert(datetime,grp.StartDateTime))-12
else (case when datepart(hh,convert(datetime,grp.StartDateTime)) = 0
then '12'
else datepart(hh,convert(datetime,grp.StartDateTime))
end)
end) as starthour,

One date check for entire query

I have the following query:
select
fp.id,
fr.id,
sum(case
when to_date(fp.offered_date) BETWEEN TO_DATE( :ad_startdate, 'YYYY-MM-DD')
AND TO_DATE(:ad_enddate, 'YYYY-MM-DD') and fp.result <> 'E'
then 1
else 0
end) total,
sum(case when fp.result = 'G'
and to_date(fp.offered_date) >= :ad_startdate
and to_date(fp.offered_date) <= :ad_enddate then 1 else 0 end) colorgreen,
sum(case when fp.resultat = 'R'
and to_date(fp.offered_date) >= :ad_startdate
and to_date(fp.offered_date) <= :ad_enddate then 1 else 0 end) colorred
FROM
fruit_properties fp, fruit fr
WHERE
fp.id = fr.id
GROUP BY
fp.id, fr.id
I'm checking dates 1 time for each sum column and have a feeling this can be made once somehow? Right now if I check only once at the total column, then colorgreen + colorred might be larger than the total since it counts no matter what date they have.
Can my query be enhanced somehow?
you can simplify like this. but PLEASE check your SQL. you're mixing TO_DATE and CHAR datatypes. this will only end in disaster.
eg you have:
when to_date(fp.offered_date) BETWEEN TO_DATE( :ad_startdate, 'YYYY-MM-DD')
AND TO_DATE(:ad_enddate, 'YYYY-MM-DD')
vs
sum(case when fp.result = 'G'
and to_date(fp.offered_date) >= :ad_startdate
in one case you are TO_DATE'ing ad_startdate but not another (so is it a date already or not?). you are also TO_DATEing the column but crucially WITHOUT a format mask. is the column really a VARCHAR datatype? if so you really should not store dates as anything but DATEs.
anyway assuming the column is a DATE datatype and the binds are of type DATE..
select fruit_prop_Id,fruit_id,
sum(case when result != 'E' then within_offer else 0 end) total,
sum(case when result = 'R' then within_offer else 0 end) colorred,
sum(case when result = 'G' then within_offer else 0 end) colorgreen
from (select fp.id fruit_id,
fr.id fruit_prop_Id,
fp.result,
case
when fp.offered_date >= :ad_startdate
and fp.offered_date <= :ad_enddate then 1 else 0 end within_offer
from fruit_properties fp, fruit fr
where fp.id = fr.id)
group by fruit_id, fruit_prop_Id
You can put the date check in the where clause:
select
fp.id,
fr.id,
sum(case when and fp.result <> 'E' then 1 else 0 end) total,
sum(case when fp.result = 'G' then 1 else 0 end) colorgreen,
sum(case when fp.resultat = 'R' then 1 else 0 end) colorred
FROM
fruit_properties fp, fruit fr
WHERE
fp.id = fr.id
AND to_date(fp.offered_date) >= :ad_startdate
AND to_date(fp.offered_date) <= :ad_enddate
GROUP BY
fp.id, fr.id
Edit: as pointed out in the comments, this query will filter out ids which doesn't have any offer dates in the given interval.