Select Case FROM Union - sql

In a purpose of reporting and creating report (MS SQL SERVER 2014) which will compare number of transactions and amounts from last day, same day last week and same day last month I need some query like this one, which is not working:
Select
Acquirer = case when Date = #Day then a.Acquirer
when Date = #LastWeekDay then b.Acquirer
when Date = #LastMonthDay then c.Acquirer
end
, RC = case when Date = #Day then a.RC
when Date = #LastWeekDay then b.RC
when Date = #LastMonthDay then c.RC
end
, Desc = case when Date = #Day then a.Desc
when Date = #LastWeekDay then b.Desc
when Date = #LastMonthDay then c.Desc
end
, Day_Tr_Count = case when Date = #Day then a.Count end
, LWD_Tr_Count = case when Date = #LastWeekDay then b.Count end
, LMD_Tr_Count = case when Date = #LastMonthDay then c.Count end
, Day_Tr_Amount = case when Date = #Day then a.Amount end
, LWD_Tr_Amount = case when Date = #LastWeekDay then b.Amount end
, LMD_Tr_Amount = case when Date = #LastMonthDay then c.Amount end
from
( select * from T1
union
select * from T2
union
select * from T3) x
group by Acquirer,RC,Desc
All 3 tables have pretty same structure:
T1,T2,T3(acquirer,RC,Desc,Count,Amount,Date).
Report should be:
result_table(Acquirer,RC,Desc,Daily_Count,Last_Week_Day_Count,Last_Month_Count,Daily_Amount,Last_Week_Day_Amount,Last_Month_Day_Amount)

Hmmm. You have an aggregation query with no group by. Perhaps:
Select v.Acquirer, v.RC, v.Desc,
Day_Tr_Count = sum(case when Date = #Day then a.Count end),
LWD_Tr_Count = sum(case when Date = #LastWeekDay then b.Count end),
LMD_Tr_Count = sum(case when Date = #LastMonthDay then c.Count end),
Day_Tr_Amount = sum(case when Date = #Day then a.Amount end
LWD_Tr_Amount = sum(case when Date = #LastWeekDay then b.Amount end),
LMD_Tr_Amount = sum(case when Date = #LastMonthDay then c.Amount end)
from (select * from T1
union all
select * from T2
union all
select * from T3
) x cross apply
(values (case when Date = #Day then a.Acquirer
when Date = #LastWeekDay then b.Acquirer
when Date = #LastMonthDay then c.Acquirer
end,
case when Date = #Day then a.RC
when Date = #LastWeekDay then b.RC
when Date = #LastMonthDay then c.RC
end,
case when Date = #Day then a.Desc
when Date = #LastWeekDay then b.Desc
when Date = #LastMonthDay then c.Desc
end
) v (Acquirer, RC, Desc)
group by v.Acquirer, v.RC, v.Desc;
Note: desc is a bad name for a column (or anything else). It is a SQL keyword (think order by).

Related

Adding between dates - sql query

Currently I have a query that will get me the data from the pervious month .
I need to change thisso I can choose a selected date range that could allow me to input 2 dates and pull back all results between them.
See my query below:
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and month(I.Date_Key) = (select case when Month (GETDATE())-1 = 0 then 12 else Month (GETDATE())-1 end)
and year(I.Date_Key) = (select case when Month (GETDATE()) -1 = 0 then year (GETDATE()) -1 ELSE YEAR (GETDATE()) end)
I need to be able to say where dates between dd/mm/yy and dd/mm/yy
You could declare the dates a variables:
Declare #Startdate as datetime
Declare #Enddate as datetime
set #Startdate = '01-AUG-20'
set #Enddate = '22-OCT-20'
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and I.Date_Key > #Startdate
and I.Date_Key < #Enddate
A simple method is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
datediff(month, i.Date_key, getdate()) = 1
That version, however, cannot use an index on i.Date_Key if that is appropriate. A more index friendly version is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
i.Date_key < datefromparts(year(getdate()), month(getdate()), 1) and
i.Date_key >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

how to fix this case sql ora-01843 not a valid month

After run sql scripts ,There's date error "ora-01843 not a valid month ", date format is (mm/dd/yyyy) this occurs on plsql, but I dont realise please see SQL statement below
SELECT COUNT(*) FROM
(SELECT c1.end_date AS eddates,cc.effectiveto,
CASE WHEN cc.effectiveto >= '1/1/4000' THEN '1/1/4000'
WHEN cc.effectiveto is null THEN '1/1/4000'
WHEN cc.effectiveto < '1/1/4000' THEN to_char(cc.effectiveto)
END mock_effectiveto
from (select aa.*,b.perm_id
from smf2.security_xref aa,
smf2.t_security_source b
where identifier_type_id = 4862
and aa.security_id = b.security_id
and b.data_source_id = 52992
AND aa.data_source_id = 52985)c1,
(Select bc.*
FROM ccc_bimbqm.instrument ab , ccc_bimbqm.identifier bc
WHERE bc.identifiertypepermid = 320015
AND ab.instrumentpermid = bc.objectpermid
AND bc.objectpermid IN
(SELECT bondid FROM ccc_muni.munibonds)) cc
WHERE c1.perm_id = cc.objectpermid
and c1.start_date = cc.effectivefrom
and cc.identifiervalue is not null
and c1.code is not NULL ) ax
WHERE ax.eddates <> mock_effectiveto
You can update your CASE statement as -
CASE WHEN cc.effectiveto = TO_DATE('01/01/4000', 'MM/DD/YYYY') OR cc.effectiveto is null
THEN TO_DATE('01/01/4000', 'MM/DD/YYYY')
WHEN cc.effectiveto < TO_DATE('01/01/4000', 'MM/DD/YYYY')
THEN to_char(cc.effectiveto)
END mock_effectiveto

Cross Join Generating Series of Dates

I am trying to count the number of tenants that renew in a month, based off of a "dtleasefrom" (lease start date). However, I want to attribute each renewal back to the month that the last lease ended, and tie it to a generated series of dates that can be used to pivot off of. However, I cannot seem to figure out why the unit_month_date doesn't equal the dtleaseto date. See pictures and code below.
Select
ten.scode as leasename
,th.sevent as event_type
,th.dtoccurred as date_occurred
,unit.scode as unit
,p.scode as property
,th.dtapply as apply_date
,th.dtapprove as approve_date
,th.dtsigndate as sign_date
,th.dtmovein as move_in_date
,th.dtmoveout as move_out_date
,th.dtleasefrom as lease_from
,th.dtleaseto as lease_to
,th.dtnotice as notice_date
,th.crent as rent
,att.subgroup2 as zone
,(ten.sfirstname || ' ' || ten.slastname) as tenant_name
,pm.property_manager as property_manager
,(case when date_trunc('month',th2.b) = dd.month::date and th2.row_numba = 1 and th.sevent = 'Lease Signed' then 1 else 0 end) as Leases_Ending
,dd.month::date as unit_month
,(case when date_trunc('month',th2.b) = dd.month::date and EXTRACT(day from age(th.dtleasefrom,th2.b)) <= 60 and EXTRACT(day from age(th.dtleasefrom,th2.b)) >= 0 and th2.row_numba = 1 and th.sevent = 'Lease Renewal' then 1 else 0 end) as Renewals
,(case when date_trunc('month',th2.b) = dd.month::date and EXTRACT(day from age(th.dtleasefrom,th2.b)) <= 60 and th2.row_numba = 1 and th.sevent = 'Lease Renewal' then 1 else 0 end) as Renewals_All_In
,(case when th.istatus not in (1,2) and date_trunc('month',th2.b) < dd.month::date and th.sevent = 'Lease Signed' then 1 else 0 end) as MTM_tenant
,th2.row_numba
,th.hmy
FROM
yardi.tenant ten
JOIN yardi.Tenant_History th on ten.hmyperson = th.htent
CROSS JOIN (SELECT generate_series('05-01-2017'::date,'01-01-2020','1 month') as month) dd
JOIN (SELECT th.htent as a , date_trunc('month',th.dtleaseto) as b, Row_Number() over(partition by th.htent order by th.hmy) as Row_Numba FROM yardi.tenant_history th group by th.htent,th.dtleaseto,th.hmy ) th2 on th2.b = dd.month and th.htent = th2.a
JOIN yardi.unit on unit.hmy = th.hunit
JOIN yardi.property p on p.hmy = unit.hproperty
JOIN yardi.attributes att on att.hprop = p.hmy
JOIN yardi.propbut_property_management pm on pm.hcode = p.hmy
WHERE ten.istatus < 6 and th2.row_numba = 1

Revenue for two months date wise

I am trying to get data for last 2 month ...but the query does not give perfect result....
SELECT DAY(table_A.PaymentDate) as date1 ,
(case when MONTH(table_A.PaymentDate) = MONTH(CURRENT_TIMESTAMP) - 1
then CAST(SUM(table_A.Total_Amount) AS INT)
else 0
end) AS last_month_CNT,
(case when MONTH(table_A.PaymentDate) = MONTH(CURRENT_TIMESTAMP)
then CAST(SUM(table_A.Total_Amount) As INT)
else 0
end) as This_month_CNT
FROM Tbl_Pan_Paymentdetails table_A
FULL OUTER JOIN Tbl_Pan_Paymentdetails table_B
ON table_A.PaymentDate=table_B.PaymentDate
WHERE YEAR(table_A.PaymentDate) = YEAR(CURRENT_TIMESTAMP)
AND
table_A.PaymentDate >= DATEADD(MONTH, -1, GETDATE())
GROUP BY
DAY(table_A.PaymentDate) ,MONTH(table_A.PaymentDate)
order by
DAY(table_A.PaymentDate);
Move the entire case expression inside the sum function and don't include the month in the group by. Also, the full outer join seems unnecessary so I removed it.
This should be what you are looking for:
SELECT
DAY(PaymentDate) as date1 ,
SUM(CASE WHEN MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP)-1 THEN CAST(Total_Amount AS INT) ELSE 0 END) AS last_month_CNT,
SUM(CASE WHEN MONTH(PaymentDate) = MONTH(CURRENT_TIMESTAMP) THEN CAST(Total_Amount AS INT) ELSE 0 END) AS This_month_CNT
FROM Tbl_Pan_Paymentdetails
WHERE YEAR(PaymentDate) = YEAR(CURRENT_TIMESTAMP)
AND PaymentDate >= DATEADD(MONTH, -1, GETDATE())
GROUP BY DAY(PaymentDate)
ORDER BY DAY(PaymentDate);

How do I use this SQL Stored Procedure to create an INSERT statement?

A workmate has given me this stored procedure and asked for help to create an sql INSERT statement based on its results, but am a little confused to some of the methods. For example, I've never seen a CASE statement in sql. I looked it up but the useage is different from what I was given.
Here is the stored procedure
if #ScheduleType Is Null
SELECT Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM Item_Schedule
INNER JOIN Lu_Schedule_Types
ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId
RIGHT OUTER JOIN LmpProjectInfo
ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1)
AND (Item_Schedule.ItemWbsElement = #WbsElement)
AND (Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType
, Lu_Schedule_Types.ScheduleTypeId
, LmpProjectInfo.PlannedQty
, LmpProjectInfo.AuthorizedQty
, LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
I am supposed to be helping him out but I'm by far a database wizard, and am a little out of my depth here. I'd really appreciate the help/advice/direction.
Thanks much!
This is quick sample that might work for you. This assumes that the table you want to insert data into takes all of the values return from the SELECT statement and that they are of the same type.
As a side note, the reason you might have got a bit confused about the CASE statements is possibly due to the fact there are two main ways to use them in SQL. CASE WHEN... like you have here and CASE #value# WHEN #result# THEN.... A little more searching on the web will lead you to some nice examples. For example this one.
INSERT INTO TABLE_NAME
(
ScheduleType,
I01,
I02,
PRD,
PlannedQty,
AuthorizedQty,
WbsElementID
)
SELECT
Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month, Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM
Item_Schedule INNER JOIN
Lu_Schedule_Types ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId RIGHT OUTER JOIN
LmpProjectInfo ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1) AND (Item_Schedule.ItemWbsElement = #WbsElement) AND
(Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType, Lu_Schedule_Types.ScheduleTypeId,
LmpProjectInfo.PlannedQty, LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
Try this one -
INSERT INTO dbo.table1 -- insert in table
(
ScheduleType
, I01
, I02
, PRD
, PlannedQty
, AuthorizedQty
, WbsElementID
)
SELECT
t.ScheduleType
, I01 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 1 THEN ItemQty END)
, I02 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 2 THEN ItemQty END)
, PRD = SUM(CASE WHEN InductionProduction = 2 THEN ItemQty END)
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
--INTO #temp_table -- or insert in temp table
FROM dbo.Item_Schedule s
JOIN dbo.Lu_Schedule_Types t ON s.ItemScheduleType = t.ScheduleTypeId
RIGHT JOIN dbo.LmpProjectInfo i ON s.ItemWbsElement = i.WbsElementID
WHERE s.IsActive = 1
AND s.ItemWbsElement = #WbsElement
AND s.ItemScheduleDate < DATEADD(d, 1, #EndDate))
AND s.ItemScheduleDate >= #StartDate
GROUP BY
t.ScheduleType
, t.ScheduleTypeId
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
ORDER BY t.ScheduleTypeId