How to get the sum of a column based on another column (SQL Server 2014) - sql

SELECT
HCT_USER_CONTRACT_NUMBER AS ContractNumber,
SUM(CASE
WHEN HIT_CURRENT_STOCK_NUMBER = '_DELIVERY'
THEN HIT_CHARGE_AMOUNT
ELSE 0
END) AS [DeliveryCharge]
FROM
TH_HIRE_CONTRACTS C
LEFT JOIN
TH_HIRE_ITEMS I on C.HCT_CONTRACT_NUMBER = I.HIT_CONTRACT_NUMBER
GROUP BY
HCT_USER_CONTRACT_NUMBER
I am including the above in the select statement but I get an error
Error converting data type varchar to real
In the hire_items table there is multiple lines for each corresponding record in the hire_contracts table, and I am trying to return a single line for each hire contract with the sum of the HIT_CHARGE_AMOUNT where the HIT_CURRENT_STOCK_NUMBER= = '_DELIVERY'. Unfortunately the DB design has a line for each hire item on the contract and in the same table a line for delivery and a line for collection for each hire contract and I just want to get the delivery charges per contract number.

Related

How to calculate Total transactions amount column with input / output type?

I have two tables : (transactions and Accounts) their columns are as shown in the picture bellow:
the Accounts table is simple just two columns ID and account name.
The important columns in the Transactions table are Amount and type, the type indicates whether the transaction is an input to the account or an output.
I want to find the current total amount (input - output) for each account with SQL.
this what I have tried but I couldn't go further:
select c.TRS_AC_ID, CompAccount, sum(Amount), Type from Accounts c
INNER JOIN Transactions t on c.TRS_AC_ID = t.TRS_AC_ID GROUP by CompAccount, Type
Instead of grouping by the type, you could use a case expression to return "input" transactions as is and "output" transactions as negative numbers:
SELECT c.TRS_AC_ID, CompAccount, SUM(CASE type WHEN 'O' THEN -1 * amount ELSE amount END)
FROM Accounts c
JOIN Transactions t on c.TRS_AC_ID = t.TRS_AC_ID
GROUP BY c.TRS_AC_ID, CompAccount
you can use the following SQL to get the result of input-output, however, if you need individual results then you can use either sub-query as well.
select
(select sum(amount) as input from transaction
where trs_ac_id = '1' and type_io = 'I'))
-
(seelect sum(amount) as output from transaction
where trs_ac_id = '2' and type_io = 'O')) as current_tot_amt
from dual;

Compare data in the same table

I have a table that stores monthly data and I would like to create a comparison between the quantity movement within a period.
Here is an example of the table
.
The SQL statement below is meant to return any changes that has happened within a period - any fund/policy partial or total loss as well as partial or total gain. I have been battling with it for a while - any help would be well appreciated.
I currently have 5 sets of unions - (where the policies and funds match and there's a difference in quantities held, where the policies exist in the previous and not in the current and vice versa and where the securities exist in the previous and not in the current and vice versa) but the other unions work save for the last couple (where the securities exist in the previous and not in the current and vice versa). It doesn't seem to return every occurrence.
SELECT distinct pc.[Client]
,pc.Policy
,cast(pc.Qty as decimal) AS CurrQ
,0 AS PrevQ
,cast(pc.Qty as decimal) - 0 AS QtyDiff
,CASE WHEN cast(pc.Qty as decimal) - 0 > 0 THEN 'Bought Units'
WHEN cast(pc.Qty as decimal) - 0 < 0 THEN 'Sold Units'
ELSE 'Unknown'
END AS TransactionType
,convert(varchar,cast(pc.[ValDate] as date),103) AS CurrValDate
,'' AS PrevValDate
FROM table pc
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103)
AND pc.Policy IN (SELECT policy
FROM table
WHERE convert(varchar(10),[ValDate],103) = convert(varchar(10),getdate()-1,103)
AND pc.[Fund] NOT IN (SELECT PM.[Fund]
FROM table pc
LEFT JOIN table pm ON pc.policy = pm.policy
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103))
AND convert(varchar,cast(pm.[ValDate] as date),103) = convert(varchar,getdate()-1,103))
As #Larnu rightly mentioned in the comment section, the extra conditions in the query changed the run from a LEFT JOIN to an INNER JOIN. I changed the code to have policy, fund and date in the ON clause:
FROM table pc
LEFT JOIN table pm ON (pc.policy = pm.policy
AND pc.fund = pm.fund
AND pc.[ValDate]-1 = pm.[ValDate])
and got rid of the sub queries.
Thanks again Larnu.

Shipping Report - Distinct Order with Two Dates - Status Missing from Table THEN

Links to the tables in the screenshot can be found at the link below:
https://www.dropbox.com/l/scl/AAAX85i7QE4zr1S-zr-_Lo00VUnIkE02XWo
First Issue:
Normally this table (See Load Tracking Table) would have a Field in Check Call Name that is "Pickup - Actual" signalling that this has been picked up. However in certain circumstances the CheckCallName will bypass the pickup and move to Delivered status. In cases like this I want to pull the query to treat the "Delivered" status in the same manner that Pickup Actual was being used.
Said another way, where kpo.loadtracking does not have Pickup - Actual in the Check Call Name field for any one order, I want to pull the Check Call Name for Delivered and the KeypointStatusDate.
Second Issue:
The DISTINCT clause does not work perfectly in my case, as an order can have the Pickup - Actual status updated multiple times. Here, we should take the oldest Keypoint Status Date. I've tried to use the MIN(KeypointStatusDate) and grouping by Order ID but I'm getting the following message
Msg 8120, Level 16, State 1, Line 14
Column 'KPO.LOAD.LoadId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The code I have currently is below. I'm new to SQL (about a week in) so apologies if this is simple.
SELECT
Distinct LOAD.LoadNumber
,LOAD.LoadId
,CustomerName
,OrderStatus
,CheckCallName
,PickedUpOn
,LoadTracking.KeypointStatusDate
,LOAD.OriginEarliest
,LOAD.DestinationEarliest
,CustomerRate
,CarrierCost
,Miles
FROM KPO.LOAD
Inner JOIN kpo.LoadExtension ON LOAD.LoadId = LoadExtension.LoadId
Inner JOIN kpo.Customer ON customer.CustomerId = LOAD.CustomerID
Inner JOIN kpo.LoadTracking ON LoadTracking.LoadId = LOAD.LoadId
WHERE
DATEDIFF(MONTH, GETDATE(), LoadTracking.KeypointStatusDate) = - 2
AND OrderStatus <> 'VOID'
AND CheckCallName = 'Pickup - Actual'
ORDER BY CustomerName, LoadNumber, LoadTracking.KeypointStatusDate
Load Tracking Table with Question Inside:
Data Result from Query:

How to design a Select statement with in line functions and single fields

I'm attempting to design a single SELECT statement that will do the following.
I'm creating a report that shows a file number, a statement value associated with the file number, a total invoice value that is built from all of the invoices associated with the file number, and then the difference between the statement and invoice values if there is one. finally it shows the payment due date.
The report is only suppose to show files where there is a difference between the total invoices and the value of the statement. It is also restricted by only invoices that are marked as Payable (not 'V'), by certain charge codes, and by not being 'FLAGGED' as being worked on.
The data is arranged into three tables. IMPSTATP is for the file level and contains the file number and statement value. The other two are the Invoice header and Invoice payable files.
Now obviously what I have below won't work, but I'm running into some difficulties visualizing a single select statement that will.
SELECT
P.OFFIV, FILEST, TOTDST, PDUEST,
sum(P.AMTPIV - P.DTDCIV),
TOTDST - sum(AMTPIV - DTDCIV)
FROM
IMPSTATP
JOIN ACCIHEDP AS H ON FILEST = H.FILEIV and BKRST = H.BKRIV
JOIN ACCIPBLP AS P ON H.INVIV = P.INVIV and H.BKRIV = P.BKRIV and H.OFFIV = P.OFFIV
WHERE
H.VDPDIV <> 'V' AND
(P.CHGPIV = '011' OR
P.CHGPIV = '012' OR
P.CHGPIV = '093') AND
P.VNNMIV <> 'FLAGGED'
GROUP BY FILEST
HAVING
TOTDST - sum(P.AMTPIV - P.DTDCIV) <> 0;
Keep in mind that this is with an old DB2 database on an IBM iSeries. Any and all suggestions would be welcome.

SQL query date column sorting issue

I am writing a SQL query which will return data of customer bills payments.
We have these payments in two different tables, one is "Bills" and other is "receipts". When my query data it shows that "receipts data" (from receipts table) in ascending order. I have two more date columns to show in result set which are "bill month" and "due date" (from bills table). When I try to apply order by on any of these mentioned columns it shows wrong data. Please help.
My query is attached below. thank you.
select distinct
bil.bill_id as Bill#, --(bill), this table has bill month and due date column
rec.receiptid as IDs, --(receipts),this table has receipt payment date,amount
sp.spaceno as spaceno,-- (space), this table has property names
lo.description as locaiton,-- (location),this table has details of property
one.name as owner_name,-- (owner), this table has owners information
bt.billtype as Particular,--(billtype),where bill types are saved
rec.rdate as Date,-- this column of receipt table showing wrong date data
dc.dr as opening,-- (DCnotes), this table has total payable amount column
rec.amount as dr,-- this column tells the paid amount
bil.amount as cr,-- this columen tell the payable amount
bil.balamount as balance,-- this column tells the net total of dr-cr columns
bil.billmonth as BillMonth,-- bill month column from bill table
bil.duedate as DueDate -- bill due date column from bill table
from
bills bil
inner join
Owners one on bil.ownerid = one.ownerid
inner join
Receipts rec on bil.spaceid = rec.propertyid
inner join
DCnotes dc on bil.spaceid = dc.property
inner join
BillTypes bt on bil.billtypeid = bt.billtypeid
inner join
Spaces sp on bil.spaceid = sp.spaceid
inner join
Locations lo on sp.locationid = lo.locationid
where
bil.siteid = '15'
This is the image of SQL query result:
This is the image of required data in report:
Please check attached images of required data and SQL query result