Joining 3 Tables in One Select Statement - sql

I have this data set with patient information/charges (Table 1).
I am looking to achieve Table 3. Table 3 shown below has:
Distinct Patient Number (Patno)
The sum of Billed Charges for each Patno (sum billed charges then group by patno)
DRG Rate from Table 2. This is just matching the DRG in Table 1 to Table 2 and getting the DRG Rate Associated with it.
Stop loss column. If the sum of Billed Charges for a patient (found in column 2) is >275000 then (SUM of Billed Charges -275000)*.195+ DRG Rate from column 3
Claim total: If there is a stop loss, then the claim total is just = to the stop loss value found in column 4. ELSE, it is equal to the DRG rate.
Note, each patient has only ONE claim, but can have multiple line items as shown in table 1.
Table 1: Raw Data
Table 2: DRG Lookup Table
Table 3: Result Table
Please let me know if you need any additional info. I know this is a lot to ask, honestly any tips/tricks advice will really help ! Thanks in advance !

You can try with this
SELECT PATNO, SUM([Billed Charges]) as BilledCharges,
DR.[DRG Rate],
CASE WHEN SUM([Billed Charges]) >275000 THEN ((SUM([Billed Charges])-275000 )*.195)+DR.[DRG Rate] ELSE 'NO' END AS StopLoss,
CASE WHEN SUM([Billed Charges]) >275000 THEN ((SUM([Billed Charges])-275000 )*.195)+DR.[DRG Rate] ELSE DR.[DRG Rate] END AS ClaimTotal
FROM raw_data AS RD
INNER JOIN DRG_Lookup_Table AS DR ON RD.DRG=DR.[DRG Code]
GROUP BY PATNO

I'm not so sure I understand the cardinality of the records in the two tables well, but this should be fine:
SELECT
t1.PATNO,
t1.[Billed Charges] AS BilledCharges,
t2.[DRG Rate],
t1.DRG,
CASE
WHEN t1.[Billed Charges] >= 275000
THEN (t1.[Billed Charges] - 275000)*.195 + t1.DRG
ELSE 0
END AS [Stop Loss],
CASE
WHEN t1.[Billed Charges] >= 275000
THEN (t1.[Billed Charges] - 275000)*.195 + t1.DRG
ELSE t2.[DRG Rate]
END AS [Claim Total]
FROM
(
SELECT PATNO, DRG, SUM([Billed Charges]) AS [Billed Charges]
FROM TABLE_1
GROUP BY PATNO, DRG
) t1
LEFT JOIN TABLE_2 t2 ON t1.DRG = t2.[DRG Code]

Since I couldn't recreate the tables I have not been able to check the code. Please try and let me know.
select patno,sum(billedcharges)billedcharges,(select drg_rate
from DRG_looking_table where drg_code=r.drg)DRG_Rate, drg,
(case when sum(billedcharges)>275000 then (sum(billedcharges)-275000)*.195+drg_rate else 'No' end) stop_loss,
(case when sum(billedcharges)>275000 then (sum(billedcharges)-275000)*.195+drg_rate else drg_rate end)Claim_Total
from raw_data GROUP BY PATNO

Related

How do I join these 3 tables, do a sum calculation and group by multiple values?

So I have these 3 tables below:
User Table:
Deposit Table:
Withdrawal Table:
Question:
How do I join these 3 tables together, having the values grouped by:
Month
Sex
Age
State
Expected Output:
As seen from my expected output above, I want to separate these users into different buckets
i.e.
Month: January, Sex: F, Age: 18, State: Arizona (Bucket 1)
Month: January, Sex: M, Age: 21, State: Texas (Bucket 2)
and find the sum(Deposit.amount) & sum (Withdrawal.amount) group by the fields above ^
as well as how many users are in this bucket.
Clarification:
"Month" column in my Expected Ouput is based on Transaction Month for both Deposit & Withdrawal table combined, I just added the "Account Created Month" column in User table just in case its possible to do a 3-table join through Month values.
This should work:
SELECT tr.Month, u.Sex, u.Age, u.Stage
, Sum(CASE WHEN [Type] = 'D' THEN tr.Amount ELSE 0 END) As [Total Deposit Amount]
, Sum(CASE WHEN [Type] = 'W' THEN tr.Amount ELSE 0 END) As [Total Withdrawal Amount]
, COUNT(distint u.UserID) As [Number of Users in this Category]
FROM (
SELECT userid, [Deposit Amount] As Amount, [Transaction Month] As Month, 'D' As [Type] FROM [Deposit]
UNION ALL
SELECT userid, [Withdrawal Amount], [Transaction Month], 'W' FROM [Withdrawal]
) tr
INNER JOIN User u ON u.UserID = tr.UserId
GROUP BY tr.Month, u.Sex, u.Age, u.State
Really, deposits and withdrawals should be the same table (Transactions) to begin with, where the only difference is withdrawals are negative.
Also... please stop using images to represent your sample data and results. It makes things so much harder on us to help you, which makes it less likely you'll get a good or prompt answer.

sql insert with multiple selects

I am trying to make an interest calculation for a loan. I have 2 tables, first table is the loan table that contains the loan amount, interest rate and other data. But interest rate changes daily and is stored on another table. So interest rate must be taken from loan tbl only if a payment is made the same day that loan is created.
Also I need to have amount remained after every payment that is store on tbl payment. So on every payment I need to fill the columns on table payment below. I tried to create a SQL statement to calculate interest rate and another to calculate the amount remained after the payment but cant combine them in one insert statement.
Example for loanid=1 , pay amount=$1000, loanid=29
SELECT
1, 1000 , date(),
(IIF(NOT ISNULL(t1.dailyinterest), t1.dailyinterest, t2.interestrate)
FROM
daily AS t1
RIGHT JOIN
loanable AS t2 ON (t1.loanid = t2.loanid AND t1.data = date())
WHERE
t2.loanid = 29)
SELECT
IIF(NOT ISNULL(pay.amountremained_tobepayed), pay.amountremained_tobepayed, 50000)
FROM
payment AS pay
RIGHT JOIN
(SELECT MAX(paymentid) AS id
FROM payment
WHERE loanid = 29) AS max2 ON pay.paymentid = max2.id
loan table
loanid
clientid
loanamount
interestrate
date
1
1
50000
0.2
05/04/20
daily interest table
clientid
loanid
date
dailyinterest
1
1
06/04/20
0.3
1
1
07/04/20
0.31
1
1
08/04/20
0.32
payment table
paymenid
loanid
amountpayed
paid_date
paid_interest
paid_pricipal
amountremained_tobepayed
Your query could look something like this.
parameters [loan id] int,
[client id] int,
[payment date] datetime,
[payment amount] currency;
insert into [payment table] (
-- payment table column names go here
)
select
-- parameters, names of columns in loan_table and
-- daily_interest_table, and calculated values go here
from loan_table
inner join daily_interest_table
on loan_table.loanid = daily_interest_table.loanid
and loan_table.clientid = daily_interest_table.clientid
where loan_table.loanid = [loan id]
and loan_table.clientid = [client id]
and daily_interest_table.date = [payment date];
I wrote below sql code but giving me error Syntax error missing operator in query
select 29, 1000 , date(), IIF(not IsNull(t1.dailyinterest) ,t1.dailyinterest, t2.interestrate) * 1000/100 AS inte, 1000 - inte as principal, amtremained
FROM daily AS t1
RIGHT JOIN loant AS t2
ON (t1.loanid = t2.loanid and t1.data= date())
inner join
(select IIF(not IsNull(pay.remainedamount), pay.remainedamount, 50000) - principal as amtremained
FROM paymentt AS pay RIGHT JOIN
(SELECT max(paymentid) AS id FROM paymentt where loanid=29) AS max2 ON pay.paymentid=max2.id)
on pay.loanid=t1.loanid

sql multiplying a sum

I'm struggling with the below code. i'm trying to work out the total balance of a folio by using its total charges and total payments. i'm almost there, however with the below code the payments is incorrect, it seems to be multiplying the total sum of payments by the number of entries in charges. i'm guessing this is because I've connected the payments and charges, which I needed to do to filter out the checkin date which is only on pms sales.
can anyone help?
thanks
SELECT DISTINCT 'PMS AD' AS APP,
FOLIO_ID,
SUM(TOTAL_CHARGES) as TOTAL_CHARGES,
SUM(TOTAL_PAYMENTS) as TOTAL_PAYMENTS
FROM ((SELECT DISTINCT P1.FOLIO_ID AS FOLIO_ID, SUM(P1.CHARGE_CODE_AMOUNT) AS TOTAL_CHARGES, 0 AS TOTAL_PAYMENTS
FROM DEV.VR_PMS_SALES P1
WHERE P1.CHARGE_CODE_AMOUNT <> 0 AND
P1.ITEM_OPERATING_DAY IS NOT NULL
AND P1.ITEM_OPERATING_DAY <= '03-DEC-2014'
AND P1.CHECKIN_DATE <= '03-DEC-2014'
GROUP BY P1.FOLIO_ID
) UNION ALL
(SELECT DISTINCT P2.FOLIO_ID AS FOLIO_ID, 0 AS TOTAL_CHARGES, SUM(P2.AMOUNT) AS TOTAL_PAYMENTS
FROM DEV.VR_PMS_PAYMENTS P2,
DEV.VR_PMS_SALES P3
WHERE P2.FOLIO_ID = P3.FOLIO_ID
AND P2.AMOUNT <> 0
AND P2.PMS_OPERATING_DAY <= '03-DEC-2014'
AND P3.CHECKIN_DATE <= '03-DEC-2014'
GROUP BY P2.FOLIO_ID
)
) F
GROUP BY FOLIO_ID
EDIT:
Sorry I didn't provide examples. table data below
VR_PMS_PAYMENTS
VR_PMS_SALES
The issue I am having is that when running the sql it is multiplying the sum of p1.amount by the number of entries in VR_PMS_SALES. eg folio 4 is returning as 165 instead of 55. I need it to return the below...
desired outcome
I hope this is clearer.
thank you

SQL Server - logic to allow me to do a calculation in the where statement

I have searched for an answer for ages with no luck for my particular problem.
I have been asked to create a script to extract data for a mail-merge. Our billing team need to identify users who we have sent final warning notices to but have still not paid their bills.
The biggest challenge that I have been unable to overcome is that some of the customers may have done one of the following:
not made any payments for the outstanding amount
paid the outstanding amount in full in one payment
paid the outstanding amount in full with multiple payments
paid part of the outstanding amount in one or multiple payments
The data that was used to generate the final warning notices is in a table with the outstanding amount appearing as a positive number, and any payments that have been made are in a different table as a negative number.
In my query identifying customers from scenario 1 and 2 would be fairly easy to identify, but 3 and 4 are causing me headaches. I had the idea of adding the outstanding amount to a sum of any payments made. If the sum total is > 0 then the customer has not paid enough to cover the outstanding amount. I have developed a sub-query to get a total of all payments made after a certain date but I can't get the query to add that to the outstanding amount and then check to see if the balance is greater than 0. Error I get is "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."
Can someone recommend a different approach to this query?
SELECT
finalwarning.table_no AS [Property No],
finalwarning.value_1 AS [Arrears Balance],
finalwarning.date_1 AS [Notice Date]
FROM
finalwarning
WHERE
finalwarning.table_no = 172030
AND finalwarning.ref_3 = 'Final'
AND ((SELECT
CASE
WHEN EXISTS (SELECT 1
FROM paymentsmade
WHERE PROPERTY_NO = 1234
AND TRANSACTION_DESC = 'Receipt'
AND TRANSACTION_DATE > '2017-05-01 00:00:00.000'
GROUP BY TRANSACTION_DESC)
THEN (SELECT SUM(amount)
FROM paymentsmade
WHERE paymentsmade.PROPERTY_NO = 1234
AND paymentsmade.TRANSACTION_DESC = 'Receipt'
AND paymentsmade.TRANSACTION_DATE > '2017-05-01 00:00:00.000'
GROUP BY paymentsmade.TRANSACTION_DESC)
ELSE '0'
END) + finalwarning.value_1) < 0
CTE are our friends and really help get the hard work done for us and allow for easier writing of the core SQL. The example below takes your structure and applies the concept of a payments CTE which will aggregate payments by property no and provide for all of the calculations you need to perform in your evaluation. I was uncertain about how the date came into play and the join might be wrong because there were 2 different numbers provided for property_no in the example but I assumed they were one and the same.
WITH paymentCTE (property_no, amount, transaction_desc, cntpayments)
as
(select property_no, sum(amount) as amount, transaction_desc, count(*)
from paymentsmade
where TRANSACTION_DATE > > '2017-05-01 00:00:00.000'
group by property_no, transaction_desc
)
SELECT fw.table_no AS [Property No]
, fw.value_1 AS [Arrears Balance]
, fw.date_1 AS [Notice Date]
, coalesce(p1.amount,0) as [Payments Made]
, fw.value_1+coalesce(p1.amount,0) as [Outstanding Balance]
, coalesce(p1.cntpayments, 0) as [Number of Payments]
FROM finalwarning fw
left outer join paymentCTE p1
on fw.table_no = p1.property_no
and p1.Transaction_desc = 'Receipt'
WHERE p1.cntpayments is null
or (coalesce(p1.cntpayments, 0) = 1 and fw.value_1 + coalesce(p1.amount,0) = 0)
or (coalesce(p1.cntpayments, 0) > 1 and fw.value_1 + coalesce(p1.amount,0) = 0)
or (coalesce(p1.cntpayments, 0) > 0 and fw.value_1 + coalesce(p1.amount,0)<> 0)

Where clause within Case Statement

I need to drill into detail on to an existing report which shows me the total profitability per customer, per month on a telecoms company.
The company sells calls, service charges and has discounts.
This is the query that I'm using, using one customer in particular:
SELECT
custumer_name,
ISNULL(SUM(CASE CONVERT(VARCHAR(10), month_end, 103)
WHEN '31/10/2016'
THEN totcall + isnull(totrec, 0) - discount
ELSE 0
END), 0) AS '31/10/2016',
SUM(totcall) AS 'Total Calls',
SUM(totrec) AS 'Total Rec',
SUM(discount) AS 'Discounts'
FROM
total_sales
INNER JOIN
customer_details ON billingaddress = customer_details .siteid
INNER JOIN
sales_month d ON total_sales.periodid = d.monthid
INNER JOIN
customer b ON customer_details .id = b.id AND b.is_customer = 1
WHERE
b.custumer_name = '2
GROUP BY
b.custumer_name
ORDER BY
b.custumer_name ASC
This is bringing back the correct total however when I need to show the drilldown of the total on calls, rec & discounts it is showing me the actual sum of every months' data which is stored on that table.
I'm not sure how can I get the last 3 columns to itemise the total without specifying the actual month (as the report has columns for the last 12 months of data.
Please help?
Thank you!
PS. The DB is a SQL Server 2008