How to get Sql Temp Table Join with column values that are not in table, replaced by 0 - sql

I have 5 temp tables that I want to combine into a new temp table via the month_year column and the prod_id. Where the columns are not prod_id or month_year and values are not available, I want that column's value(e.g. job_amt or received_qty) to be 0.
#tmp_spoilt_good_job_amt
month_year job_amt spoil good prod_id
07-2017 40 10 20 2
08-2017 827 0 210 3
09-2017 27 1 27 2
09-2017 732 22 345 3
10-2017 50 0 6 2
10-2017 1130 55 50 3
11-2017 300 0 0 4
#tmp_received_qty
month_year received_qty prod_id
08-2017 32 2
08-2017 2500 3
09-2017 2200 2
11-2017 2500 4
#tmp_purchase_qty
month_year purchase_qty prod_id
09-2017 11 2
#tmp_opening_balance
month_year opening_balance prod_id
08-2017 32 2
08-2017 2500 3
09-2017 22 2
09-2017 2300 3
10-2017 2163 2
10-2017 2023 3
11-2017 2500 4
#tmp_closing_balance
month_year closing_balance prod_id
08-2017 2300 3
08-2017 32 2
09-2017 2213 2
09-2017 1998 3
10-2017 1687 3
10-2017 2163 2
11-2017 2400 4
I tried some inner joins but the values were repeating or some were not reflecting. what query could I use to get these combined?
I am looking for the following output:

CREATE TABLE #table_with_all_months_prod_ids_using_cross_join (month_year, prod_id)
GO
INSERT #table_with_all_months_prod_ids_using_cross_join
SELECT t1.month_year, t2.prod_id
FROM monthyeartable t1
CROSS JOIN prodidtable t2
SELECT DISTINCT t0.month_year, t0.prod_id, ISNULL(t1.job_amt,0), ISNULL(t1.spoil,0), ISNULL(t1.good,0), ISNULL(t2.received_qty,0), ISNULL(t3.purchase_qty,0), ISNULL(t4.opening_balance,0), ISNULL(t5.closing_balance,0)
FROM #table_with_all_months_prod_ids_using_cross_join t0
LEFT JOIN #tmp_spoilt_good_job_amt t1 ON t0.month_year = t1.month_year AND t0.prod_id = t1.prod_id
LEFT JOIN #tmp_received_qty t2 ON t0.month_year = t2.month_year AND t0.prod_id = t2.prod_id
LEFT JOIN #tmp_purchase_qty t3 ON t0.month_year = t3.month_year AND t0.prod_id = t3.prod_id
LEFT JOIN #tmp_opening_balance t4 ON t0.month_year = t4.month_year AND t0.prod_id = t4.prod_id
LEFT JOIN #tmp_closing_balance t5 ON t0.month_year = t5.month_year AND t0.prod_id = t5.prod_id
WHERE NOT (t1.job_amt IS NULL AND t1.spoil IS NULL AND t1.good IS NULL AND t2.received_qty IS NULL AND t3.purchase_qty IS NULL AND t4.opening_balance IS NULL AND t5.closing_balance IS NULL)

So, this kind of relation ships have very week performance, first of all it is better to change the tables structure and all other thing that related to fill data in you database.
Any way, this query created for your current needs with current data structure, also if you work on this query or divided it in to some views maybe you can improve performance:
SELECT CASE WHEN ISNULL(srpo.month_year , '-1') <> '-1' THEN srpo.month_year
WHEN ISNULL(c.month_year , '-1') <> '-1' THEN c.month_year
END AS month_year,
CASE WHEN ISNULL(srpo.prod_id, -1) <> -1 THEN srpo.prod_id
WHEN ISNULL (c.prod_id, -1) <> -1 THEN c.prod_id
END AS prod_id,
CASE WHEN ISNULL(c.closing_balance, -1) = -1 THEN 0 else c.closing_balance END AS closing_balance,
srpo.job_amt,srpo.spoil,srpo.good ,srpo.received_qty,srpo.purchase_qty, srpo.opening_balance
FROM #tmp_closing_balance AS c FULL OUTER JOIN
(SELECT CASE WHEN ISNULL(srp.month_year , '-1') <> '-1' THEN srp.month_year
WHEN ISNULL(o.month_year , '-1') <> '-1' THEN o.month_year
END AS month_year,
CASE WHEN ISNULL(srp.prod_id, -1) <> -1 THEN srp.prod_id
WHEN ISNULL (o.prod_id, -1) <> -1 THEN o.prod_id
END AS prod_id,
CASE WHEN ISNULL(o.opening_balance, -1) = -1 THEN 0 else o.opening_balance END AS opening_balance,
srp.job_amt,srp.spoil,srp.good ,srp.received_qty,srp.purchase_qty
FROM #tmp_opening_balance AS o FULL OUTER JOIN
(SELECT CASE WHEN ISNULL(sr.month_year , '-1') <> '-1' THEN sr.month_year
WHEN ISNULL(p.month_year , '-1') <> '-1' THEN p.month_year
END AS month_year,
CASE WHEN ISNULL(sr.prod_id, -1) <> -1 THEN sr.prod_id
WHEN ISNULL (p.prod_id, -1) <> -1 THEN p.prod_id
END AS prod_id,
CASE WHEN ISNULL(p.purchase_qty, -1) = -1 THEN 0 else p.purchase_qty END AS purchase_qty,
sr.job_amt,sr.spoil,sr.good ,sr.received_qty
FROM #tmp_purchase_qty AS p FULL OUTER JOIN
(SELECT CASE WHEN ISNULL(s.month_year , '-1') <> '-1' THEN s.month_year
WHEN ISNULL(r.month_year , '-1') <> '-1' THEN r.month_year
END AS month_year,
CASE WHEN ISNULL(s.prod_id, -1) <> -1 THEN s.prod_id
WHEN ISNULL (r.prod_id, -1) <> -1 THEN r.prod_id
END AS prod_id,
CASE WHEN ISNULL(s.job_amt, -1) = -1 THEN 0 else s.job_amt END AS job_amt,
CASE WHEN ISNULL(s.spoil, -1) = -1 THEN 0 else s.spoil END AS spoil,
CASE WHEN ISNULL(s.good, -1) = -1 THEN 0 else s.good END AS good,
CASE WHEN ISNULL(r.received_qty, -1) = -1 THEN 0 else r.received_qty END AS received_qty
FROM #tmp_spoilt_good_job_amt AS s FULL OUTER JOIN
#tmp_received_qty AS r ON s.prod_id = r.prod_id AND
LTRIM(rtrim(s.month_year)) = LTRIM(rtrim(r.month_year))) AS sr ON
sr.prod_id = p.prod_id AND LTRIM(rtrim(sr.month_year)) = LTRIM(rtrim(p.month_year)) ) AS srp ON
srp.prod_id = o.prod_id AND LTRIM(rtrim(srp.month_year)) = LTRIM(rtrim(o.month_year))) AS srpo ON
srpo.prod_id = c.prod_id AND LTRIM(rtrim(srpo.month_year)) = LTRIM(rtrim(c.month_year))
I use FULL OUTER JOIN for all part of query because you mentioned that, may be all tables have possible values for keys columns(month_year and prod_id).

First if you have these 5 temp tables that probably means there is a much much much better way of doing this at the source table level! But because you asked you most significant problem with combining them is that not 1 of the tables hold a combination of every month_year and prod_id. So you have to create it. The way I choose to do this for completeness sake is to:
Create a Tally table (as a common table expression [CTE]) for use in
generating a month_year table
Create a Products CTE by unioning all distinct prod_ids from your temp tables
Create a MonthYearInputs CTE to be able to determine the Max and Min month_years represented
Generate a MonthYear CTE to house every possible month_year combination between the MIN & MAX years represented in your data
Then a cartisean (CROSS) join between the MonthYear & Product ctes give you all of the combinations to LEFT JOIN the other tables to.
Simply put a where statement in to remove the rows that have no values in ALL of the tables and use ISNULL() or COALESCE() to make the null values 0.
Here is a working example: http://rextester.com/MCEO96178
;WITH cteTen AS (
SELECT n FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)
, cteTally AS (
SELECT
n = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM
cteTen t1
CROSS JOIN cteTen t2 --hundreds
CROSS JOIN cteTen t3 --thousands
--keep cross joining if need more than 1000 month
)
, cteProducts AS (
SELECT DISTINCT prod_id FROM #tmp_spoilt_good_job_amt
UNION
SELECT DISTINCT prod_id FROM #tmp_received_qty
UNION
SELECT DISTINCT prod_id FROM #tmp_purchase_qty
UNION
SELECT DISTINCT prod_id FROM #tmp_opening_balance
UNION
SELECT DISTINCT prod_id FROM #tmp_closing_balance
)
, cteInputMonthYears AS (
SELECT DISTINCT month_year FROM #tmp_spoilt_good_job_amt
UNION
SELECT DISTINCT month_year FROM #tmp_received_qty
UNION
SELECT DISTINCT month_year FROM #tmp_purchase_qty
UNION
SELECT DISTINCT month_year FROM #tmp_opening_balance
UNION
SELECT DISTINCT month_year FROM #tmp_closing_balance
)
, cteMaxMinMonthYears AS (
SELECT
MinMonthYear = CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME)
,MonthsDiff = DATEDIFF(MONTH,CAST(STUFF(MIN(month_year),3,0,'-01') AS DATETIME),CAST(STUFF(MAX(month_year),3,0,'-01') AS DATETIME)) + 1
FROM
cteInputMonthYears
)
, cteMonthYears AS (
SELECT
month_year = FORMAT(DATEADD(MONTH, t.n - 1, m.MinMonthYear),'MM-yyyy')
FROM
cteMaxMinMonthYears m
INNER JOIN cteTally t
ON m.MonthsDiff >= t.n
)
SELECT
my.month_year
,job_amt = ISNULL(ja.job_amt,0)
,spoil = ISNULL(ja.spoil,0)
,good = ISNULL(ja.good,0)
,p.prod_id
,received_qty = ISNULL(r.received_qty,0)
,purchase_qty = ISNULL(pur.purchase_qty,0)
,opening_balance = ISNULL(o.opening_balance,0)
,closing_balance = ISNULL(c.closing_balance,0)
FROM
cteMonthYears my
CROSS JOIN cteProducts p
LEFT JOIN #tmp_spoilt_good_job_amt ja
ON my.month_year = ja.month_year
AND p.prod_id = ja.prod_id
LEFT JOIN #tmp_received_qty r
ON my.month_year = r.month_year
AND p.prod_id = r.prod_id
LEFT JOIN #tmp_purchase_qty pur
ON my.month_year = pur.month_year
AND p.prod_id = pur.prod_id
LEFT JOIN #tmp_opening_balance o
ON my.month_year = o.month_year
AND p.prod_id = o.prod_id
LEFT JOIN #tmp_closing_balance c
ON my.month_year = c.month_year
AND p.prod_id = c.prod_id
WHERE
NOT(ja.month_year IS NULL
AND r.month_year IS NULL
AND pur.month_year IS NULL
AND o.month_year IS NULL
AND o.month_year IS NULL
AND c.month_year IS NULL)
ORDER BY
my.month_year
,p.prod_id

Personally, I think you should go with #influent's suggest: derive a template table on to which you can left the values you're looking for.
In the eventuality that you don't have the required logic or data to accurately derive such a template table, there is another option.
1. Pad out each table with dummy 0 values, so that they all have the same fields
2. UNION all the tables together
3. GROUP all the results back down to one row per month per product
WITH
padded_combined
AS
(
SELECT month_year, prod_id, job_amt, spoil, good, 0 AS received_qty, 0 AS purchase_qty, 0 AS opening_balance, 0 AS closing_balance FROM #tmp_spoilt_good_job_amt
UNION ALL
SELECT month_year, prod_id, 0, 0, 0, received_qty, 0, 0, 0 FROM #tmp_received_qty
UNION ALL
SELECT month_year, prod_id, 0, 0, 0, 0, purchase_qty, 0, 0 FROM #tmp_purchase_qty
UNION ALL
SELECT month_year, prod_id, 0, 0, 0, 0, 0, opening_balance, 0 FROM #tmp_opening_balance
UNION ALL
SELECT month_year, prod_id, 0, 0, 0, 0, 0, 0, closing_balance FROM #tmp_closing_balance
)
SELECT
month_year,
prod_id,
SUM(job_amt) AS job_amt,
SUM(spoil) AS spoil,
SUM(good) AS good,
SUM(received_qty) AS received_qty,
SUM(purchase_qty) AS purchase_qty,
SUM(opening_balance) AS opening_balance,
SUM(closing_balance) AS closing_balance
FROM
padded_combined
GROUP BY
month_year,
prod_id
ORDER BY
month_year,
prod_id

Related

Sql optimization query with join on Presto

I have the following query which shows out of all the clicks on products how many no of products have >1 image. The queries separately work fine but when combined its not able to execute within 3m threshold time. Any inputs how can this be optimized best.
select DATE (DATE_TRUNC('week',dt)) AS wk_dt,COUNT(DISTINCT a.product_id) tot_prods,COUNT(DISTINCT b.product_id) multiimp_prods,count(a.product_id) AS total_clicks,count(case when b.product_id>0 then a.product_id END) AS total_mulimg_clicks
from (
select product_id,DATE(from_unixtime((time/1000)+19800)) as dt--,count(distinct_id) clicks
from silver.mixpanel_android__product_clicked
WHERE DATE(from_unixtime((time/1000)+19800)) BETWEEN date(date_trunc('week',cast(Current_date - interval '14' day AS date))) AND Current_date
GROUP BY 1,2) a --2,471,245 1,458,476
LEFT join (
SELECT product_id,tot_img
FROM (SELECT DISTINCT product_id, catalog_id,(a + b + c + d + e) AS tot_img
FROM (
SELECT product_id,catalog_id,
CASE WHEN images is NULL then 0 else 1 end as a,
CASE WHEN img_2 is NULL then 0 else 1 end as b,
CASE WHEN img_3 is NULL then 0 else 1 end as c,
CASE WHEN img_4 is NULL then 0 else 1 end as d,
CASE WHEN img_5 is NULL then 0 else 1 end as e
FROM (
SELECT DISTINCT id AS product_id,catalog_id,
TRIM(images) AS images,
TRIM(SPLIT_PART(images,',',2)) AS "img_2",
TRIM(SPLIT_PART(images,',',3)) AS "img_3",
TRIM(SPLIT_PART(images,',',4)) AS "img_4",
TRIM(SPLIT_PART(images,',',5)) AS "img_5"
FROM silver.supply__products --WHERE date(created) <= date(date_trunc('week',cast(Current_date - interval '14' day AS date)))
)
--GROUP BY 1,2
order by 6 asc
)
)
WHERE tot_img>1
) b
on a.product_id=b.product_id
GROUP BY 1

INCORRECT SUM() OUTPUT on LEFT JOIN CASE QUERY

when i select the specific table and use the case method to get only the max value of 8 there is no problem with it.
but when i use the 1st query and join it to get the SUM value of totalhrs it gave me different value
REFERENCE TABLE WORKING
SELECT l1.userid,(l2.fname+' '+l2.lname) as empname,l2.department,l1.date,MIN(l1.time_in) as timein,MAX(l1.time_in) as timeout,CASE WHEN DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0 > 8 THEN 8 ELSE DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0 END as totalhrs
,CASE WHEN DATEDIFF(minute,'08:00',MIN(l1.time_in)) > 0 THEN DATEDIFF(minute,'08:00',MIN(l1.time_in)) ELSE 0 END as late,
CASE WHEN DATEDIFF(minute,MAX(l1.time_in),'17:00') > 0 THEN DATEDIFF(minute,MAX(l1.time_in),'17:00') ELSE 0 END as undertime,MAX(image_in) as imgo,MIN(image_in) as imgi
from hgs_hr_attendancelogs l1
LEFT JOIN (SELECT userid,lname,fname,department from user_acc)l2
ON l1.userid = l2.userid
WHERE l1.userid = '442' and l1.date between '2021-03-16' and '2021-03-31'
group by l1.userid,l1.date,l2.fname,l2.lname,l2.department
ORDER BY l1.userid
OUTPUT IN SUM INSTEAD ADD THE 4th column(THE SUM IS 78) it gives 2668.17
SELECT l1.userid,SUM(l2.totalhrs),COUNT(l2.late)
FROM hgs_hr_attendancelogs l1
LEFT JOIN(SELECT l1.userid,(l2.fname+' '+l2.lname) as empname,l2.department,l1.date,MIN(l1.time_in) as timein,MAX(l1.time_in) as timeout,
CAST(CASE WHEN DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0 > 8 THEN 8 ELSE DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0 END as DECIMAL(18,2)) totalhrs
,CASE WHEN DATEDIFF(minute,'08:00',MIN(l1.time_in)) > 0 THEN DATEDIFF(minute,'08:00',MIN(l1.time_in)) ELSE 0 END as late,
CASE WHEN DATEDIFF(minute,MAX(l1.time_in),'17:00') > 0 THEN DATEDIFF(minute,MAX(l1.time_in),'17:00') ELSE 0 END as undertime,MAX(image_in) as imgo,MIN(image_in) as imgi
from hgs_hr_attendancelogs l1
LEFT JOIN (SELECT userid,lname,fname,department from user_acc)l2
ON l1.userid = l2.userid
group by l1.userid,l1.date,l2.fname,l2.lname,l2.department ) l2
ON l1.userid = l2.userid
WHERE l2.date between '2021-03-16' and '2021-03-31'
GROUP BY l1.userid
Think you dont need the second join hgs_hr_attendancelogs (in not working query). A query like below should work. please check.
select
t1.userid, SUM(t1.totalhrs),COUNT(t1.late)
from
(
--working
SELECT
l1.userid,(l2.fname+' '+l2.lname) as empname,l2.department,l1.date,MIN(l1.time_in) as timein,MAX(l1.time_in) as timeout,
CASE
WHEN DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0 > 8
THEN 8
ELSE
DATEDIFF(MINUTE,CONVERT(datetime,MIN(l1.time_in)) ,CONVERT(datetime,MAX(l1.time_in)))/60.0
END as totalhrs,
CASE
WHEN DATEDIFF(minute,'08:00',MIN(l1.time_in)) > 0
THEN DATEDIFF(minute,'08:00',MIN(l1.time_in))
ELSE
0
END as late,
CASE
WHEN DATEDIFF(minute,MAX(l1.time_in),'17:00') > 0
THEN DATEDIFF(minute,MAX(l1.time_in),'17:00')
ELSE
0
END as undertime,
MAX(image_in) as imgo,
MIN(image_in) as imgi
from
hgs_hr_attendancelogs l1
LEFT JOIN (SELECT userid,lname,fname,department from user_acc)l2 ON l1.userid = l2.userid
WHERE
l1.userid = '442'
and l1.date between '2021-03-16' and '2021-03-31'
group by
l1.userid,l1.date,l2.fname,l2.lname,l2.department
) t1
group by
l1.userid
ORDER BY
l1.userid
And reg the 'query not working', did you try moving the l2.date between '2021-03-16' and '2021-03-31' inside the left join?
Thanks

issues in Case and when Statement

I have a question about Case and when statements. I have a list of two transtypeid like 10 and 12.
I tried to take sale1 amount like if the transtypeid 11 has a sum amount !=0 means, I need to minus the amount with sum amount of transtypeid 10
I tried a lot but nothing worked.
I have these queries I tried
select
CT.CustomerCode, C.CustomerName,
sale1 = case
when (ct.TransTypeID = 11) and (sum(ct.OVAmount - ct.OVDiscount) != 0)
then sum(ct.OVAmount - ct.OVDiscount) - sum(ct.OVAmount - ct.OVDiscount)
else 0
end,
C.CountryCode, C.CityCode
from
CustomerTransactions CT
inner join
Customers C ON CT.CustomerCode = C.CustomerCode
where
ct.TransDate >= '2015-01-01'
and ct.TransDate <= '2015-12-31'
and ct.TransTypeID in (10, 11)
group by
ct.CustomerCode, c.CustomerName, c.CountryCode, c.CityCode
Try calculate sale1 with this SQL code:
CASE WHEN
SUM(CASE WHEN ct.TransTypeID = 11
THEN ct.OVAmount - ct.OVDiscount
ELSE 0 END) != 0
THEN
SUM(CASE WHEN ct.TransTypeID = 11
THEN ct.OVAmount - ct.OVDiscount
ELSE O END)
- SUM(CASE WHEN ct.TransTypeID = 10
THEN ct.OVAmount - ct.OVDiscount
ELSE 0 END)
ELSE 0 END
I'm not sure that I understand what you need. But I give it a try since you are in hurry.
Something like this, maybe?
select
CT1.CustomerCode, C.CustomerName,
sale1 =
case
when ( sum(ct1.OVAmount - ct1.OVDiscount) != 0 )
then sum( ct1.OVAmount - ct1.OVDiscount ) - sum( ct2.OVAmount - ct2.OVDiscount )
else
0
end,
C.CountryCode, C.CityCode
from
Customers c
Inner join CustomerTransactions CT1 ON ( CT1.CustomerCode = C.CustomerCode ) And ( ct1.TransTypeID = 11 )
Inner join CustomerTransactions CT2 ON ( CT2.CustomerCode = C.CustomerCode ) And ( ct2.TransTypeID = 10 )
where
( ct1.TransDate >= '2015-01-01' )
and ( ct1.TransDate < '2016-01-01' )
and ( ct2.TransDate >= '2015-01-01' )
and ( ct2.TransDate < '2016-01-01' )
group by
ct1.CustomerCode,c.CustomerName,c.CountryCode,c.CityCode
Using CTEs:
with
cte10 ( CustomerId, amount ) as (
select
customerId, sum( amount ) as amount
from
CustomerTransaction
where
( Type = 1 )
group by CustomerId
),
cte11 ( CustomerId, amount ) as (
select
customerId, sum( amount ) as amount
from
CustomerTransaction
where
( Type = 2 )
group by CustomerId
)
select
c.Id, c.Description,
sale1 =
case
when ( cte10.amount <> 0 )
then cte10.amount - cte11.amount
else
0
end
from
Customer c
Inner join cte10 on ( cte10.CustomerId = C.id )
inner join cte11 on ( cte11.Customerid = C.id )

sql join and group by generated date range

I have Table1 and I need a query to populate Table2:
Problem here is with Date column. I want to know the process of location/partner combination per day. Main issue here is that I can't pick DateCreated and make it as default date since it doesn't necessarily cover whole date range, like in this example where it doesn't have 2015-01-07 and 2015-01-09. Same case with other dates.
So, my idea is to first select dates from some table which contains needed date range and then perform calculation for each day/location/partner combination from cte but in that case I can't figure out how to make a join for LocationId and PartnerId.
Columns:
Date - CreatedItems - number of created items where Table1.DateCreated = Table2.Date
DeliveredItems - number of delivered items where Table1.DateDateOut = Table2.Date
CycleTime - number of days delivered item was in the location (DateOut - DateIn + 1)
I started with something like this but it's very like that I completely missed the point with it:
with d as
(
select date from DimDate
where date between DATEADD(DAY, -365, getdate()) and getdate()
),
cr as -- created items
(
select
DateCreated,
LocationId,
PartnerId,
CreatedItems = count(*)
from Table1
where DateCreated is not null
group by DateCreated,
LocationId,
PartnerId
),
del as -- delivered items
(
select
DateOut,
LocationId,
ParnerId,
DeliveredItems = count(*),
CycleTime = DATEDIFF(Day, DateOut, DateIn)
from Table1
where DateOut is not null
and Datein is not null
group by DateOut,
LocationId,
PartnerId
)
select
d.Date
from d
LEFT OUTER JOIN cr on cr.DateCreated = d.Date -- MISSING JOIN PER LocationId and PartnerId
LEFT OUTER JOIN del on del.DateCompleted = d.Date -- MISSING JOIN PER LocationId and PartnerId
with range(days) as (
select 0 union all select 1 union all select 2 union all
select 3 union all select 4 union all select 5 union all
select 6 /* extend as necessary */
)
select dateadd(day, r.days, t.DateCreated) as "Date", locationId, PartnerId,
sum(
case
when dateadd(day, r.days, t.DateCreated) = t.DateCreated
then 1 else 0
end) as CreatedItems,
sum(
case
when dateadd(day, r.days, t.DateCreated) = t.Dateout
then 1 else 0
end) as DeliveredItems,
sum(
case
when dateadd(day, r.days, t.DateCreated) = t.Dateout
then datediff(days, t.DateIn, t.DateOut) + 1 else 0
end) as CycleTime
from
<yourtable> as t
inner join range as r
on r.days between 0 and datediff(day, t.DateCreated, t.DateOut)
group by dateadd(day, r.days, t.DateCreated), LocationId, PartnerId;
If you only want the end dates (rather than all the dates in between) this is probably a better approach:
with range(dt) as (
select distinct DateCreated from T union
select distinct DateOut from T
)
select r.dt as "Date", locationId, PartnerId,
sum(
case
when r.dt = t.DateCreated
then 1 else 0
end) as CreatedItems,
sum(
case
when r.dt = t.Dateout
then 1 else 0
end) as DeliveredItems,
sum(
case
when r.dt = t.Dateout
then datediff(days, t.DateIn, t.DateOut) + 1 else 0
end) as CycleTime
from
<yourtable> as t
inner join range as r
on r.dt in (t.DateCreated, t.DateOut)
group by r.dt, LocationId, PartnerId;
If to specify WHERE clause? Something Like that:
WHERE cr.LocationId = del.LocationId AND
cr.PartnerId = del.PartnerId

Update Value without cursor

I have a table in the database.
Bill
ID Total Paid Status
1 1000 1000 Paid
2 500 400 Part Paid
3 700 0 Unpaid
4 200 0 Unpaid
Now the User pays PAID_AMT -> $900, which i want to distribute such that my table looks:
ID Total Paid Status
1 1000 1000 Paid
2 500 500 Paid
3 700 700 Paid
4 200 100 Part Paid
It can be easily done using cursor, but i want to avoid cursors.
Is it possible to achieve this using simple update queries with Output parameters.
Something like this
Update Bill
Set Paid = Total,
Status = 'Paid',
Output PAID_AMT = PAID_AMT - (Total-Paid )
where Total-Paid > PAID_AMT
The following query shows the amount owed, assuming SQL Server 2012:
select b.*,
sum(total - paid) over (order by id) as cumNotPaid
from bill b
You can now distribute the amount:
select b.*,
(case when cumNotPaid >= #AMOUNT then 0
when cumNotPaid - toBePaid <= #AMOUNT then toBePaid
else #AMOUNT - cumnotPaid
end) as PaidAmount
from (select b.*,
sum(total - paid) over (order by id) as cumNotPaid,
total - paid as ToBePaid
from bill b
) b
Now, this is an updatable CTE, so we can use this in an update statement:
with toupdate as (
(select b.*,
(case when cumNotPaid >= #AMOUNT then 0
when cumNotPaid - toBePaid <= #AMOUNT then toBePaid
else #AMOUNT - cumnotPaid
end) as PaidAmount
from (select b.*,
sum(total - paid) over (order by id) as cumNotPaid,
total - paid as ToBePaid
from bill b
) b
)
update toupdate
set paid = PaidAmount,
status = (case when total = paid then 'Paid' when total = 0 then 'UnPaid'
else 'PartPaid'
end);
I don't know what version of SQL server do you, if it 2008 then you could not use rolling sum with window function. You can try this recursive query:
declare #paid_amount int = 900
;with cte1 as (
select
b.id,
b.total - b.paid as diff,
row_number() over(order by id) as row_num
from Bill as b
where b.total <> b.paid
), cte2 as (
select
c1.id, c1.row_num, #paid_amount - c1.diff as paid_amount
from cte1 as c1
where c1.row_num = 1
union all
select
c1.id, c1.row_num, c2.paid_amount - c1.diff as paid_amount
from cte1 as c1
inner join cte2 as c2 on c2.row_num + 1 = c1.row_num
where c2.paid_amount > 0
)
update Bill set
Paid =
case
when c.paid_amount >= 0 then b.Total
else b.Total - b.Paid + c.paid_amount
end,
Status = case when c.paid_amount >= 0 then 'Paid' else 'Part Paid' end
from Bill as b
inner join cte2 as c on c.id = b.id
sql fiddle demo
for SQL server 2012 it's a bit easier:
declare #paid_amount int = 900
;with cte1 as (
select
b.id,
b.total - b.paid as amount_to_pay,
sum(b.total - b.paid) over(order by b.id) as amount
from Bill as b
where b.total <> b.paid
), cte2 as (
select
c.id,
#paid_amount - c.amount as remain_amount
from cte1 as c
where #paid_amount - c.amount + c.amount_to_pay >= 0
)
update Bill set
Paid =
case
when c.remain_amount >= 0 then b.Total
else b.Total - b.Paid + c.remain_amount
end,
Status = case when c.remain_amount >= 0 then 'Paid' else 'Part Paid' end
from Bill as b
inner join cte2 as c on c.id = b.id;
sql fiddle demo
If you are using SQL 2012 you can use the following:
DECLARE #PayAmount INT = 900;
WITH Dues AS
(
SELECT *, Total-Paid AS Due
FROM Bill
)
, Cumulative AS
(
SELECT *, SUM(Due) OVER (ORDER BY Id) AS CumulativeTotalDue
FROM Dues
)
, Payable AS
(
SELECT *, #PayAmount - CumulativeTotalDue AS AmountLeftAfterPaying
FROM Cumulative
)
, BillWithAmountToApplyRaw AS
(
SELECT *
, CASE
WHEN AmountLeftAfterPaying >= 0 THEN Due
ELSE Due + AmountLeftAfterPaying
END AS RawAmountToApply
FROM Payable
)
, BillWithAmountToApply AS
(
SELECT *, CASE WHEN RawAmountToApply < 0 THEN 0 ELSE RawAmountToApply END AS AmountToApply
FROM BillWithAmountToApplyRaw
)
That will give you the amount to apply in the AmountToApply column.
So you can use the above as
UPDATE BillWithAmountToApply
SET Paid = Paid + AmountToApply
FROM BillWithAmountToApply
(Use
SELECT *
FROM BillWithAmountToApply
to check it out first if you want)
SQL 2008 Version (less efficient because of the repeated joins, which aren't necessary in 2012):
WITH Dues AS
(
SELECT *, Total-Paid AS Due
FROM Bill
)
, CumulativeDue AS
(
SELECT base.Id, SUM(cumulative.Due) AS CumulativeTotalDue
FROM Dues base
JOIN Dues cumulative ON cumulative.Id <= base.Id
GROUP BY base.Id
)
, Cumulative AS
(
SELECT Dues.*, CumulativeDue.CumulativeTotalDue
FROM Dues
JOIN CumulativeDue ON CumulativeDue.Id = Dues.Id
)
... as above
Schema objects:
--BEGIN TRAN;
--CREATE TABLE Bill
--(
-- ID Int PRIMARY KEY IDENTITY,
-- Total INT NOT NULL,
-- Paid INT NOT NULL DEFAULT(0),
-- Status AS
-- CASE
-- WHEN Paid = Total THEN 'Paid'
-- WHEN Paid = 0 THEN 'Unpaid'
-- ELSE 'Part Paid'
-- END
--);
--WITH KnownValues(Total, Paid) AS
--(
-- SELECT 1000, 1000
-- UNION ALL SELECT 500, 400
-- UNION ALL SELECT 700, 0
-- UNION ALL SELECT 200, 0
--)
--INSERT INTO Bill(Total, Paid)
--SELECT *
--FROM KnownValues;
--COMMIT