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

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.

Related

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

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.

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:

MS Access-Return Record Below Current Record

I am very new to Access, and what I am trying to do seems like it should be very simple, but I can't seem to get it.
I am a structural engineer by trade and am making a database to design buildings.
My Diaphragm Analysis Table includes the fields "Floor_Name", "Story_Number", "Wall_Left", and "Wall_Right". I want to write a new query that looks in another query called "Shear_Wall_incremental_Deflection" and pulls information from it based on input from Diaphragm Analysis. I want to take the value in "Wall_Right" (SW01), find the corresponding value in "Shear_Wall_incremental_Deflection", and report the "Elastic_Deflection" corresponding to the "Story_Below" instead of the "Story_Number" in the Diaphragm Analysis Table. In the case where "Story_Number" = 1, "Story_Below" will be 0 and I want the output to be 0.
Same procedure for "Wall_Left", but I'm just taking it one step at a time.
It seems that I need to use a "DLookup" in the expression builder with TWO criteria, one that Wall_Right = Shear_Wall and one that Story_Number = Story_Below, but when I try this I just get errors.
"Shear_Wall_incremental_Deflection" includes shearwalls for all three stories, i.e. it starts at SW01 and goes through SWW for Story Number 3 and then starts again at SW01 for Story Number 2, and so on until Story Number 1. I only show a part of the query results in the image, but rest assured, there are "Elastic_Deflection" values for story numbers below 3.
Here is my attempt in the Expression Builder:
Right_Defl_in: IIf(IsNull([Diaphragm_Analysis]![Wall_Right]),0,DLookUp("[Elastic_Deflection_in]","[Shear_Wall_incremental_Deflection]","[Shear_Wall_incremental_Deflection]![Story_Below]=" & [Diaphragm_Analysis]![Story_Number]))
I know my join from Diaphragm_Analysis "Wall_Left" and "Wall_Right" must include all records from Diaphragm_Analysis and only those from "Shear_Wall_incremental_Deflection"![Shear_Walls] where the joined fields are equal, but that's about all I know.
Please let me know if I need to include more information or send out the database file.
Thanks for your help.
Diaphragm Analysis (Input Table)
Shear_Wall_incremental_Deflection (Partial Image of Query)
I think what you are missing is that you can and should join to Diaphragm_Analysis twice, first time to get the Story_Below value and second to use it to get the corresponding Elastic_Deflection value.
To handle the special case where Story_Below is zero, I would write a separate query (only requires one join this time) and 'OR together' the two queries using the UNION set operation (note the following SQL is untested):
SELECT swid.Floor_Name,
swid.Story_Number,
swid.Wall_Left,
da2.Elastic_Deflection AS Story_Below_Elastic_Deflection
FROM ( Shear_Wall_incremental_Deflection swid
INNER JOIN Diaphragm_Analysis da1
ON da1.ShearWall = swid.Wall_Left )
INNER JOIN Diaphragm_Analysis da2
ON da2.ShearWall = swid.Wall_Left
AND da2.Story_Number = da1.Story_Below
UNION
SELECT swid.Floor_Name,
swid.Story_Number,
swid.Wall_Left,
0 AS Story_Below_Elastic_Deflection
FROM Shear_Wall_incremental_Deflection swid
INNER JOIN Diaphragm_Analysis da1
ON da1.ShearWall = swid.Wall_Left
WHERE da1.Story_Below = 0;
I've assumed that there is no data where Story_Number is zero.

Sql server View with while statement

I`m learning to use SQL and this is my second question, hope it make sense! :)
My problem:
When I check a customer’s order, I need to know If it would be fully allocated (pre-shipped ) or not.
The DB hasn’t the progression of the allocated quantity, but only the allocated quantity for each order, and the total ordered to-be-allocated from the customers.
The orders will be allocated by: order priority, confirmation date, internal order number.
This is where I get so far:
SELECT dbo.MA_SaleOrdDetails.Item, dbo.MA_SaleOrdDetails.Description,
dbo.MA_SaleOrdDetails.Qty, dbo.MA_SaleOrdDetails.Allocated,
CASE WHEN dbo.MA_SaleOrdDetails.Allocated > dbo.MA_SaleOrdDetails.DeliveredQty
THEN dbo.MA_SaleOrdDetails.Qty - dbo.MA_SaleOrdDetails.DeliveredQty - dbo.MA_SaleOrdDetails.Allocated
ELSE dbo.MA_SaleOrdDetails.Qty - dbo.MA_SaleOrdDetails.DeliveredQty END AS TOALLOCATE,
dbo.MA_SaleOrd.InternalOrdNo, dbo.MA_SaleOrd.ConfirmedDeliveryDate,
dbo.MA_SaleOrd.Customer, dbo.MA_SaleOrd.Priority,
dbo.MA_SaleOrdDetails.SaleOrdId, dbo.MA_SaleOrdShipping.Carrier1,
dbo.MA_SaleOrdShipping.ShipToAddress,
dbo.MA_ItemsFiscalData.FinalOnHand AS InitialAvailability
FROM dbo.MA_SaleOrdDetails
INNER JOIN dbo.MA_SaleOrd
ON dbo.MA_SaleOrdDetails.SaleOrdId = dbo.MA_SaleOrd.SaleOrdId
INNER JOIN dbo.MA_SaleOrdShipping
ON dbo.MA_SaleOrd.SaleOrdId = dbo.MA_SaleOrdShipping.SaleOrdId
INNER JOIN dbo.MA_ItemsFiscalData
ON dbo.MA_ItemsFiscalData.Item = dbo.MA_SaleOrdDetails.Item
WHERE (dbo.MA_SaleOrdDetails.Delivered = '0')
AND (dbo.MA_SaleOrdDetails.Invoiced = '0')
AND (dbo.MA_SaleOrdDetails.Cancelled = '0')
AND (dbo.MA_ItemsFiscalData.FiscalYear = YEAR(GETDATE()))
ORDER BY dbo.MA_SaleOrdDetails.Item, dbo.MA_SaleOrd.Priority,
dbo.MA_SaleOrd.ConfirmedDeliveryDate, dbo.MA_SaleOrd.InternalOrdNo
Now I want to calculate at each row in a new column named “progression” the progression of the quantity that will be allocated.
The progression should be:
For the first listed item = InitialAvailability – TOALLOCATE
For every row with same item = previous TOALLOCATE – TOALLOCATE
And restart every item change
I’ve tried with a WHILE statement but I could not make it work.
Im all yours :)

Access Update not working

I have an Access Database which links into Excel for a college database project. The goal is to fix incorrect/incomplete data before importation through the use of Update/SQL queries. There is one item in particular which is a field containing the order status. If an order is complete = Complete, if an order is missing a few parts = Backorder and nothing at all = Open. The issue I have is there is multiple parts on one PO ID# which makes it difficult to determine if an order is on backorder as 2/5 parts may be complete while 3/5 may be on backorder. Any ideas on how I can force access to automatically set a default order status or is this a long sql query?
Thanks
With SQL you can return a query to find the order status, using a CASE statement. I'm not sure of the table/column names in the parent table you have but you can probably tweak it from here (I'm just assuming identity columns):
SELECT P.Id, P.Name, "Status" =
CASE
WHEN R.QuantityReceived < I.QuantityOrdered THEN 'Backorder'
WHEN R.QuantityReceived = I.QuantityOrdered THEN 'Complete'
WHEN R.QuantityReceived > I.QuantityOrdered THEN 'Open'
END
FROM PurchaseOrders P INNER JOIN POItem I on P.PurchaseOrderId = I.PurchaseOrderId
INNER JOIN POReceipt R on I.ItemId = R.ItemId
So first you need to join your tables to get the related records (this is also assuming that there is only one of each), then use a CASE statement to return the value you are looking for based on a comparison between fields.