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
Related
In the first column (Report_Date) of this query the date is being constructed and is today's day, and is used in the following lines to select is the following columns. I'd like to use a specific day in the query.
I'd like help to write the format to replace column 1 (Report_Date) with a different date to create aging, like June 1st - 2021-06-01.
SELECT
convert(datetime,convert(char,datepart(mm,getdate()))+'/'+convert(char,datepart(dd,getdate()))+'/'+convert(char,datepart(yyyy,getdate())))Report_Date,
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 0 and 30 then B.CurrentBalance else 0
end) '0-30',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 31 and 60 then B.CurrentBalance else 0
end) '31-60',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 61 and 90 then B.CurrentBalance else 0
end) '61-90',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 91 and 120 then B.CurrentBalance else 0
end) '91-120',
B.Primary_Payer_Code,
B.Secondary_Payer_Code,
B.CurrentResponsibility_desc,
Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP
Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else
F.Description End End
FROM
Date D with (nolock)
JOIN TEL_BILLED_LINE_ITEM_ODS B with (nolock) ON ( convert(datetime,convert(char,B.Original_Bill_Date,101)) = D.DATE)
LEFT OUTER JOIN TBLPAYER_ODS P with (nolock) ON B.Primary_Payer_Code=P.Code
LEFT OUTER JOIN TBLFINANCIALCLASS_ODS F with (nolock) ON F.tblfinancialclassid = P.FinancialClassID
LEFT OUTER JOIN PAYER_GROUP G ON G.PAYER_CODE = P.CODE
WHERE
( B.CurrentBalance != 0)
AND B.BadDebtFlagYN=0
AND B.Primary_Payer_Code !='CL' -- exclude CLIENT 07/01/2010 jdw
GROUP BY
B.Primary_Payer_Code,
B.Secondary_Payer_Code,
B.CurrentResponsibility_desc,
Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP
Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else
F.Description End End
I wrote this code to get the number of risks with different status but I don't want the result in multiple rows, I just added the C_INSERTTIME field in order to filter the time later. how can i get the result in one row?
SELECT rsk.C_INSERTTIME inserttime,
SUM(CASE
WHEN rskst.c_code = 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS drafted_risk,
SUM(CASE
WHEN rskst.c_code <> 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS analyzed_risk,
SUM(CASE
WHEN rskdecsass.c_code = 'HSE_DECISION_ASSESSMENT_APPROVED' THEN 1
ELSE 0
END) AS approved_assessed_risks
FROM T_HSE_RISK rsk
LEFT JOIN t_hse_category_element rskst ON rskst.c_id = rsk.f_category_element_id_rsk_stts
LEFT JOIN t_hse_category_element rskdecsass ON rskdecsass.c_id = rsk.F_CTGRY_ELMNT_ID_DCSN_ASSSSMNT
WHERE rsk.C_INSERTTIME >= TIMESTAMP '2000-01-01 00:00:00'
GROUP BY rsk.C_INSERTTIME
You should remove the GROUP BY and use aggregation on C_inserttime as follows:
SELECT min(rsk.C_INSERTTIME) inserttime, -- or max
SUM(CASE
WHEN rskst.c_code = 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS drafted_risk,
SUM(CASE
WHEN rskst.c_code <> 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS analyzed_risk,
SUM(CASE
WHEN rskdecsass.c_code = 'HSE_DECISION_ASSESSMENT_APPROVED' THEN 1
ELSE 0
END) AS approved_assessed_risks
FROM T_HSE_RISK rsk
LEFT JOIN t_hse_category_element rskst ON rskst.c_id = rsk.f_category_element_id_rsk_stts
LEFT JOIN t_hse_category_element rskdecsass ON rskdecsass.c_id = rsk.F_CTGRY_ELMNT_ID_DCSN_ASSSSMNT
WHERE rsk.C_INSERTTIME >= TIMESTAMP '2000-01-01 00:00:00'
-- GROUP BY rsk.C_INSERTTIME -- removed this
I have a query that does not return the expense value if the drvalue(Debtor Value) is equal to 0 or NULL,
If i change the drvalue to any value greater than 0, query returns the expenses value.
Drvalue is a sum of all the values for a specific period
Below is the query
SELECT f.vehiclenumber,f.fleettype,f.IsCreditor,
ISNULL(SUM(l.DrValue),0) AS drvalue,
CASE WHEN iscreditor=1 then Sum (DrValue) - Sum(CrValue) else null end AS Profit,
sum(l.CrValue) AS CrValue ,
sum(l.distance) AS LoadDist,
sum(l.DrValue)/DDist AS DRVal ,
d.Liters AS Liters,d.ddist AS DDist, d.DDiesel AS DDiesel, d.DieselCost AS dieslCost,
(MAX(isnull(l.Closingkm,0))-MIN(isnull(l.OpeningKM,0))) AS [CO],ISNULL(SUM(l.DrValue),0) / CASE WHEN (isnull(MAX(l.Closingkm),0)-MIN(isnull(l.OpeningKM,0)))=0 THEN 1 ELSE (isnull(MAX(l.Closingkm),0)-MIN(isnull(l.OpeningKM,0))) END AS TotalCPK,
(d.DieselCost/sum(l.DrValue)) * 100 AS DieselPerc,
SUM(jobdetails.total) AS Expenses,
count(l.vehicleNo) AS LoadCount
FROM tblVehicle AS f
LEFT JOIN (SELECT Vehicleno, loaddate, DrValue, CrValue,Distance, OpeningKM, closingkm FROM tblloads WHERE DrValue IS NOT NULL) AS l ON f.VehicleNumber = l.VehicleNo AND l.loaddate >= '2020-06-01' and l.loaddate <= '2020-06-30'
LEFT JOIN (SELECT fleet , NULLIF(SUM(Liters),0) AS Liters,NULLIF(sum(distance),0) AS DDist, NULLIF(sum(distance)/ CASE WHEN sum(Liters)=0 THEN 1 ELSE sum(Liters) END,0) AS DDiesel, NULLIF(SUM (Manual_Amount),0) AS DieselCost FROM tblinput
WHERE [Date] >= '2020-06-01' And [Date] <= '2020-06-30'
GROUP BY Fleet) AS d ON l.VehicleNo = d.Fleet
LEFT JOIN (SELECT jd.fleet, SUM(Total) AS total From tblJobDetails jd, tbljobcards WHERE tbljobcards.JobID = jd.jobid AND jobdate >= '2020-06-01' AND jobdate <= '2020-06-30' GROUP BY jd.fleet) AS jobdetails ON jobdetails.fleet = l.vehicleno
WHERE VehicleCategory <> 'T'
GROUP BY f.vehiclenumber,f.fleettype,f.IsCreditor,d.Liters,d.ddist, d.DDiesel,d.DieselCost
ORDER BY fleettype
RESULTS
I have query that that references a dynamic calander table, it updates aged periods based on the current date. I am using this table in another query, it sum's sales value based on aged QTR's. These values will update as time passes and I can assign colmn names such as 'AGED1Q' but I would like to find a way to use the actual period name from the calander table. Any sugestions will be greatly appreciated.
Current query is below, I have added a few comment lines where I would like to make the changes. Thanks again
SELECT dbo.CUSTOMER_ORDER.CUSTOMER_ID AS CUST_ID,
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-4', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-3', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-2', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-1', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1) THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS 'TOTAL'
FROM dbo.CUSTOMER_ORDER LEFT OUTER JOIN
dbo.UFC_Calander LEFT OUTER JOIN
dbo.UCC_CALENDAR_TODAY_BASED_AGING ON dbo.UFC_Calander.DAY = dbo.UCC_CALENDAR_TODAY_BASED_AGING.DATES ON
dbo.CUSTOMER_ORDER.ORDER_DATE = dbo.UFC_Calander.DAY LEFT OUTER JOIN
dbo.CUSTOMER ON dbo.CUSTOMER_ORDER.CUSTOMER_ID = dbo.CUSTOMER.ID RIGHT OUTER JOIN
dbo.PART RIGHT OUTER JOIN
dbo.CUST_ORDER_LINE ON dbo.PART.ID = dbo.CUST_ORDER_LINE.PART_ID ON dbo.CUSTOMER_ORDER.ID = dbo.CUST_ORDER_LINE.CUST_ORDER_ID
WHERE (dbo.CUSTOMER_ORDER.STATUS <> 'x') AND dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1)
GROUP BY dbo.CUSTOMER_ORDER.CUSTOMER_ID
HAVING (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'UNFOCO') AND (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'QUOTE')
ORDER BY TOTAL DESC
I am just learning SQL and have run into a problem creating a custom report. I am working with school attendance data. I want to create a report that gives membership days and number of days for each absence type.
I have successfully created a report for these separately.
Membership Days (calculated by counting days school was in session between the student's entry date and the current date. Membership days does not exist as a field on its own)
SELECT sum(case when cd.DATE_VALUE >= s.ENTRYDATE and cd.DATE_VALUE <= current_timestamp THEN cd.INSESSION ELSE 0 END), s.LASTFIRST
FROM CALENDAR_DAY cd,STUDENTS s
WHERE cd.SCHOOLID = 405
GROUP BY s.LASTFIRST
Count per absence type
SELECT s.STUDENT_NUMBER, s.LASTFIRST,SUM(CASE WHEN a.ATTENDANCE_CODEID = 2 THEN 1 ELSE 0 END),SUM(CASE WHEN a.ATTENDANCE_CODEID = 4 THEN 1 ELSE 0 END),SUM(CASE WHEN a.ATTENDANCE_CODEID = 3 THEN 1 ELSE 0 END),SUM(CASE WHEN a.ATTENDANCE_CODEID = 51 THEN 1 ELSE 0 END)
FROM ATTENDANCE a
INNER join STUDENTS s
ON a.STUDENTID = s.ID
WHERE a.att_date between '%param1%' and '%param2%'
GROUP BY s.STUDENT_NUMBER, s.LASTFIRST
The problem is that if I try to put these in the same report, the membership days are multiplied by the number of times the student appears in the attendance table due to joining student and attendance. My thought on a solution was to then divide this line
sum(case when cd.DATE_VALUE >= s.ENTRYDATE and cd.DATE_VALUE <= current_timestamp THEN cd.INSESSION ELSE 0 END)
by the number of times the student showed up in the attendance table to counteract the student information existing on every line. I can't figure out how to do that. I don't know much about these types of problems, so hopefully I've just gone off on the wrong track and there is an easy solution. Thanks.
Your problem is a common problem -- trying to summarize along two dimensions at the same time without using a subquery. You want to do this query with two aggregation subqueries. Something like this:
SELECT *
FROM (SELECT sum(case when cd.DATE_VALUE >= s.ENTRYDATE and cd.DATE_VALUE <= current_timestamp
THEN cd.INSESSION
ELSE 0
END), s. STUDENT_NUMBER
FROM CALENDAR_DAY cd CROSS JOIN
STUDENTS s
WHERE cd.SCHOOLID = 405
GROUP BY s.STUDENT_NUMBER
) sc JOIN
(SELECT s.STUDENT_NUMBER, s.LASTFIRST,
SUM(CASE WHEN a.ATTENDANCE_CODEID = 2 THEN 1 ELSE 0 END),
SUM(CASE WHEN a.ATTENDANCE_CODEID = 4 THEN 1 ELSE 0 END),
SUM(CASE WHEN a.ATTENDANCE_CODEID = 3 THEN 1 ELSE 0 END),
SUM(CASE WHEN a.ATTENDANCE_CODEID = 51 THEN 1 ELSE 0 END)
FROM ATTENDANCE a INNER join
STUDENTS s
ON a.STUDENTID = s.ID
WHERE a.att_date between '%param1%' and '%param2%'
GROUP BY s.STUDENT_NUMBER, s.LASTFIRST
) sa
on sc.STUDENT_NUMBER = sa.STUDENT_NUMBER;