I'm trying to do a calculation on a what-if basis, so I assumed I could've done this using the case when function. Such as:
SELECT
TRIM(EXTRACT(YEAR FROM business_date))||'Q'||TRIM((EXTRACT(MONTH FROM business_date)+2)/3) as year_qtr,
case when orr_txt = '1' then (sum(cast (rr9m as float)) / (sum(cast (total_observations as float)) - 0.5*sum(cast (lft as float)) )) end as DR_1,
case when orr_txt = '2' then (sum(cast (rr9m as float)) / (sum(cast (total_observations as float)) - 0.5*sum(cast (lft as float)) )) end as DR_2,
case when orr_txt = '3' then (sum(cast (rr9m as float)) / (sum(cast (total_observations as float)) - 0.5*sum(cast (lft as float)) )) end as DR_3,
avg(cast (dp as float)) as Pred_PD
FROM
raroc.pd_matrixRR a,
raroc.ccc_dp_sc b,
raroc.ratings_convert c
WHERE
start_orr_code in (1)
and case when a.scorecard_group = 'BB' then 'Business Banking' else a.scorecard_group end= b.rating_sys
and a.orr_txt = b.bacrr
and a.orr_txt = c.bacrr_text
and orr_txt not in ('9-', '10', '11', '12', 'NR')
and rating_sys_grp = 'Scorecard'
--and a.orr_txt = '1'
--and scorecard_group = 'Large Corporation'
--and scorecard_group = 'Large Corporation_FI'
--and scorecard_group = 'Middle Market'
--and scorecard_group = 'BB'
--and scorecard_group = 'GCSBB'
--and scorecard_group = 'Real Estate'
and scorecard_group = 'Individuals'
and scorecard_group not like 'Sove%'
and scorecard_group not like 'Lega%'
--and year_qtr < '2014Q2'
group by 1,2,3,4
ORDER BY 2,1
It apparently didn't compile and laughed at my logic. However, I'll get an error 3604 if I don't group it. The question is, how would I get about this in order to calculate the rate for category 1, 2, and 3.
Much appreciated!
SP
You need to move the CASE inside the aggregate function like this:
(sum(case when orr_txt = '1' then cast (rr9m as float) end)
/ (sum(case when orr_txt = '1' then cast (total_observations as float) end)
- 0.5*sum(case when orr_txt = '1' then cast (lft end as float) end ) )) end as DR_1,
I think you just want conditional aggregation. The conditions go inside the aggregation functions. I think this is the expression that you want (repeated 3 times of course for each value:
SELECT . . .
(sum(case when orr_txt = '1' then cast(rr9m as float) end) /
sum(case when orr_txt = '1' then cast(total_observations as float) end) -
0.5 * sum(case when orr_txt = '1' then cast(lft as float) end)
) as DR_1, . . .
You can then change the GROUP BY to GROUP BY 1.
You have to group by
group by
TRIM(EXTRACT(YEAR FROM business_date))||'Q'||TRIM((EXTRACT(MONTH FROM business_date)+2)/3)
, orr_txt
Related
When I use the below query I only get percentage column but I want the (buyer_id, buyer_name, created_date,total_work_orders_with_gtv_first_60_days, total_gtv_first_60_days, total_net_amount_first_60_days) to show as columns too. Would really appreciate your help please.
WITH results_cte AS (
SELECT
b.buyer_id,
b.buyer_name,
CAST(b.created_date AS DATE) AS created_date,
COALESCE(wo.total_work_orders_with_gtv_first_60_days, 0) AS total_work_orders_with_gtv_first_60_days,
COALESCE(wo.total_gtv_first_60_days, 0) AS total_gtv_first_60_days,
COALESCE(wo.total_net_amount_first_60_days, 0) AS total_net_amount_first_60_days
FROM dw.buyer b
LEFT JOIN (SELECT wo.buyer_id,
COUNT(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.work_order_id ELSE NULL END) AS total_work_orders_with_gtv_first_60_days,
SUM(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.gtv ELSE NULL END) AS total_gtv_first_60_days,
SUM(CASE WHEN wo.gtv_date < DATEADD(DAY, 60, b.created_date) THEN wo.net_amount ELSE NULL END) AS total_net_amount_first_60_days
FROM dw.work_order wo
JOIN dw.buyer b
ON wo.buyer_id = b.buyer_id
WHERE wo.gtv > 0
GROUP BY wo.buyer_id) wo
ON b.buyer_id = wo.buyer_id
WHERE b.buyer_segmentation = 'S - Self-Service'
AND b.status = 'Active'
AND b.created_date >= DATEADD(YEAR, -1, GETDATE())
)
SELECT (SELECT CAST(count(DISTINCT buyer_id) AS float) FROM results_cte WHERE total_work_orders_with_gtv_first_60_days > 0)
/ (SELECT CAST(count(DISTINCT buyer_id) AS float) FROM results_cte ) AS percentage
I am using SQL Server 2012.
Here is my query, I want the ordering in this order and not alphabetical.
Here is the order I want them in :
Foreign,
Out of State,
Texas,
Unknown,
Total Enrollment
I used order by cases, but I am getting an error:
Incorrect syntax near '5'
How do I fix it?
Query :
declare #Term int = 20172;
select
[Category], [Last_Term], [Current_Term], [#Change], [%Change]
from
(select
[Category],
cast(round(((cast(y.Last_Term as float)) * 1), 2) as varchar(10)) as 'Last_Term',
cast(round(((cast(y.Current_Term as float)) * 1), 2) as varchar(10)) as 'Current_Term',
cast(round(((cast(y.Current_Term as float) -
cast(y.Last_Term as float)) * 1), 2) as varchar(10)) as '#Change',
cast(round((((cast(y.Current_Term as float) -
cast(y.Last_Term as float)) /
(cast(y.Last_Term as float))) * 100), 2) as varchar(10)) + '%' as '%Change'
from
(select
Category,
Case
when year = substring(CAST (#Term- 10 as Varchar(10)),1,4)
then 'Current_Term'
when year = substring(CAST (#Term - 20 as Varchar(10)),1,4)
then 'Last_Term'
End As ACAD_YEAR,
a.enroll
from
(select
case
when dh.HOME = 'F'
then 'Foreign'
when dh.HOME = 'O'
then 'Out of State'
when dh.Home = 'I'
then 'texas'
when dh.Home = 'U'
then 'UnKnown'
end as Category,
(CONVERT(INT, SUBSTRING(ACADEMIC_PERIOD, 1, 4))) - 1 as year,
count(*) as enroll
from
[IR_DW].[dbo].[dw_enrollment_F] d
inner join
dim_Time t on d.TIME_KEY = t.TIME_KEY
inner join
dim_Home dh on d.HOME_KEY = dh.HOME_KEY
inner join
dim_Student_Level sl on d.STUDENT_LEVEL_KEY = sl.STUDENT_LEVEL_KEY
where
ACADEMIC_PERIOD_ALL = #Term - 10
or ACADEMIC_PERIOD_ALL = #Term
group by
dh.HOME, (CONVERT(INT,SUBSTRING(ACADEMIC_PERIOD,1,4))) - 1) a
) src
PIVOT
(SUM(Enroll) FOR ACAD_YEAR in ([Current_Term] , [Last_Term])) y
) a
order by
case
when a.[Category] = 'Foreign' then 1
when a.[Category] = 'Out of State' then 2
when a.[Category] = 'Texas' then 3
when a.[Category] = 'Unknown' then 4
You are missing and END though you are missing the 5 case as well...
when a.[Category] = 'Total Enrollment' then 5
ORDER BY
case when a.[Category] = 'Foreign' then 1
when a.[Category] = 'Out of State' then 2
when a.[Category] = 'Texas' then 3
when a.[Category] = 'Unknown' then 4
when a.[Category] = 'Total Enrollment' then 5 --added this
else 6 --catch all to make anything that fell outside of these categories unsorted afterwards
end --added here
Hi I have the code below which brings through a total by due and complete as well as the date. However I want to summarize by date, please can someone assist?
SELECT CONVERT(varchar(15), GRLastDt, 111) as Date_,
(
SELECT COUNT(*) AS Expr1
FROM dbo.AN_Admin_VendorReturns_090_Final
WHERE (Complete = 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
) AS Complete,
(
SELECT COUNT(*) AS Expr1
FROM dbo.AN_Admin_VendorReturns_090_Final AS AN_Admin_VendorReturns_090_Final_1
WHERE (Complete <> 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
) AS DUE
FROM dbo.AN_Admin_VendorReturns_090_Final
group by CONVERT(varchar(15), GRLastDt, 111)
SELECT CGRLastDt as Date_,
SUM(CASE WHEN Complete = 'X' Then 1 Else 0 END) AS Complete,
SUM(CASE WHEN Complete <> 'X' Then 1 Else 0 END) AS Due
FROM dbo.AN_Admin_VendorReturns_090_Final
WHERE GRLastDt >= GETDATE() - 60
GROUP BY GRLastDt
Please note that I haven't validated this SQL for syntax and doing this in notepad.
My running query is
select
to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,
(case when (sum(fs.shipping_fee) < 0) then (-sum(fs.shipping_fee))else
sum(fs.shipping_fee) END) as Shipping_Fee_Charged ,
(case when (sum(se.shipping_fee) < 0) then (-sum(se.shipping_fee)) else
sum(se.shipping_fee) END) as Standard_Shipping_Charges ,
(case when (sum(fs.shipping_fee - se.shipping_fee) < 0) then (-
sum(fs.shipping_fee - se.shipping_fee)) else sum(fs.shipping_fee -
se.shipping_fee) END) as Error
from
"meta".fk_Payment as fs
join
"meta".ship_error as se
on
fs.order_item_id = se.order_item_id
where
(fs.order_status = 'delivered' and se.shipping_fee != 0 and(fs.shipping_fee-se.shipping_fee)< 0)
and
to_char(se.order_date, 'YYYY') = '2015'
and
to_char(se.order_date, 'Mon') = 'Feb'
group by
fs.order_item_id
limit 10;
as describe in above query calculate the column Shipping_Fee_Charged , Standard_Shipping_Charges , Error and show only 10 rows. Now i want to sum these column again, only 10 row .
How i can do this ?
You can use a subquery to store the result in a temporary table (T1 in the code below) and from that resultset find the sum
SELECT SUM(T1.Shipping_Fee_Charged), SUM(T1.Standard_Shipping_Charges), SUM(T1.Error)
FROM (
SELECT
to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,
(case when (sum(fs.shipping_fee) < 0) then (-sum(fs.shipping_fee))else
sum(fs.shipping_fee) END) as Shipping_Fee_Charged ,
(case when (sum(se.shipping_fee) < 0) then (-sum(se.shipping_fee)) else
sum(se.shipping_fee) END) as Standard_Shipping_Charges ,
(case when (sum(fs.shipping_fee - se.shipping_fee) < 0) then (-
sum(fs.shipping_fee - se.shipping_fee)) else sum(fs.shipping_fee -
se.shipping_fee) END) as Error
FROM "meta".fk_Payment as fs
JOIN "meta".ship_error as se ON fs.order_item_id = se.order_item_id
WHERE (fs.order_status = 'delivered' and se.shipping_fee != 0 and(fs.shipping_fee-se.shipping_fee)< 0) AND to_char(se.order_date, 'YYYY') = '2015' AND to_char(se.order_date, 'Mon') = 'Feb'
GROUP BY fs.order_item_id
LIMIT 10
) AS T1
You can also use WITH Queries (Common Table Expressions), which is similar to the above
WITH shipping_details AS (
SELECT
to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,
.
.
)
SELECT SUM(Shipping_Fee_Charged), SUM(Standard_Shipping_Charges), SUM(Error) FROM shipping_details
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,