Query for remaining balance - sql

Query for remaining balance
I am using SQLITE 3.1.1
The scenario is the ff:
Let us say Total Quantity is 11.
The formula should be:
Total Quantity - Quantity Used = Remaining
It should look like this:
First: 11 - 1 = 10
Second: 10- 6 = 4
Third: 4 - 0 = 4
and so on..
Expected Result:
Also, Remaining value can't be lower than 0.
I currently have this SQL query but it doesn't get the Remaining query result for the next transaction but rather it always starts with Total Quantity.
SELECT
filter_maintenance.maintenance_id,
filter_maintenance.stock_id,
filter_maintenance.quantity_used,
filter_maintenance.date_registered,
filter_maintenance.date_changed,
inventories.stock_name,
SUM(inventories_order.order_quantity) - filter_maintenance.quantity_used AS Remaining
FROM filter_maintenance
INNER JOIN inventories ON filter_maintenance.stock_id = inventories.stock_id
INNER JOIN inventories_order ON filter_maintenance.stock_id = inventories_order.stock_id
GROUP BY filter_maintenance.maintenance_id
This is the output I currently have:
Your help is greatly appreciated. Thank you in advance.

Since you are using sqllite and there are no window functions you need to use a self-join instead. I assume maintenance_id is a primary key in filter_maintenance.
SELECT
filter_maintenance.maintenance_id,
filter_maintenance.stock_id,
filter_maintenance.quantity_used,
filter_maintenance.date_registered,
filter_maintenance.date_changed,
inventories.stock_name,
sum(inventories_order.order_quantity) - filter_maintenance.sum_quantity_used AS Remaining
FROM
(
SELECT fm1.*,
sum(fm2.quantity_used) AS sum_quantity_used
FROM filter_maintenance fm1
INNER JOIN filter_maintenance fm2 ON fm1.stock_id = fm2.stock_id and
fm1.date_registered >= fm2.date_registered
GROUP BY fm1.maintenance_id
) filter_maintenance
INNER JOIN inventories ON filter_maintenance.stock_id = inventories.stock_id
INNER JOIN inventories_order ON filter_maintenance.stock_id = inventories_order.stock_id
GROUP BY filter_maintenance.maintenance_id

Related

MS Access Query - Display All Rows from Original Joined Table

I need to write a query that displays ALL revenue centers for a month whether they have revenue or not. This seems like a simple request but I have seemed to hit a brick wall. Below is my SQL:
SELECT ID_ItemNominal, ItemNominal_Description, Sum(Nz([ITM_Net],0)) AS ITM_Net_Total
FROM TSub_ItmNominal LEFT JOIN (T_Invoice RIGHT JOIN T_LineItems ON T_Invoice.ITM_Reference = T_LineItems.ITM_Reference) ON TSub_ItmNominal.ID_ItemNominal = T_LineItems.ITM_Nominal
WHERE (((Year([ITM_Date]))=[report_year] Or (Year([ITM_Date])) Is Null) AND ((Month([ITM_Date]))=[report_month]))
GROUP BY TSub_ItmNominal.ID_ItemNominal, TSub_ItmNominal.ItemNominal_Description
HAVING (((TSub_ItmNominal.ID_ItemNominal) Like "4*"))
ORDER BY TSub_ItmNominal.ID_ItemNominal;
ID_ItemNominal = the Integer code for the Revenue Center
ItemNominal_Description = the description of the Revenue Center
ITM_Net = the Currency amount for the Line Item on the Invoice, to be SUM for a month total
ITM_ Date = the Date of the Invoice
My thought was to use the LEFT JOIN to say that I want to see ALL of the revenue centers, even if those records do not have any data for that month. What I get is the centers that DO have revenue for the year but DO NOT have revenue for the month are not shown / filtered out.
What the Current query provides:
40500 | Sales - Digital | $###.##
40700 | Sales - Misc | $###.##
40800 | Sales - Mail | $###.##
40900 | Sales - Clothing| $0.00
We have not done any revenue under 40900 this year so far so it shows as a result in the query. We have done revenue in 40600 this year but not for the month of April. The 40600 seems to be filtered out by the WHERE part of the query as well as any other revenue centers that we have revenue for the year but not the selected date.
I would like to see these revenue centers included in the query but show as $0.00 for the month.
Any help would be greatly appreciated, I feel like I am close but I just can't seem to get the correct results. Thank you in advance!
You could join the original table with all rows and join your query to it like
SELECT t1.ID_ItemNominal, t1.ItemNominal_Description,t2.ITM_Net_Total
FROM TSub_ItmNominal AS t1 LEFT JOIN (SELECT ID_ItemNominal, ItemNominal_Description, Sum(Nz([ITM_Net],0)) AS ITM_Net_Total
FROM TSub_ItmNominal LEFT JOIN (T_Invoice RIGHT JOIN T_LineItems ON T_Invoice.ITM_Reference = T_LineItems.ITM_Reference) ON TSub_ItmNominal.ID_ItemNominal = T_LineItems.ITM_Nominal
WHERE (((Year([ITM_Date]))=[report_year] Or (Year([ITM_Date])) Is Null) AND ((Month([ITM_Date]))=[report_month]))
GROUP BY TSub_ItmNominal.ID_ItemNominal, TSub_ItmNominal.ItemNominal_Description
HAVING (((TSub_ItmNominal.ID_ItemNominal) Like "4*")) ) AS t2 ON t1.ID_ItemNominal = t2.ID_ItemNominal
WHERE ((([t1l].[ID_ItemNominal]) Like "4*"))
ORDER BY t1.ID_ItemNominal;
Usually, when you run LEFT JOIN + WHERE you run an analogous INNER JOIN. But according to your specifications, the sub items table should be optionally joined since it can contain actual sales data not exhaustive of all revenue centers.
Therefore, run the WHERE filtering within a subquery and then have this subquery left joined to main set of revenue centers. Also, for readability below converts RIGHT JOIN to LEFT JOIN and uses table aliases instead of full table names.
SELECT main.ITM_Nominal,
main.ItemNominal_Description,
SUM(NZ(sub.[ITM_Net], 0)) AS ITM_Net_Total
FROM (T_LineItems AS main
LEFT JOIN T_Invoice AS inv
ON inv.ITM_Reference = main.ITM_Reference)
LEFT JOIN (
SELECT ID_ItemNominal, [ITM_Net]
FROM TSub_ItmNominal
WHERE ID_ItemNominal ALIKE '4%'
AND YEAR([ITM_Date]) = [report_year]
AND MONTH([ITM_Date]) = [report_month]
) AS sub
ON sub.ID_ItemNominal = main.ITM_Nominal
GROUP BY main.ITM_Nominal,
main.ItemNominal_Description
ORDER BY main.ITM_Nominal;

SQL Server - Need to SUM values in across multiple returned records

In the following query I am trying to get TotalQty to SUM across both the locations for item 6112040, but so far I have been unable to make this happen. I do need to keep both lines for 6112040 separate in order to capture the different location.
This query feeds into a Jasper ireport using something called Java.Groovy. Despite this, none of the PDFs printed yet have been either stylish or stained brown. Perhaps someone could address that issue as well, but this SUM issue takes priority
I know Gordon Linoff will get on in about an hour so maybe he can help.
DECLARE #receipt INT
SET #receipt = 20
SELECT
ent.WarehouseSku AS WarehouseSku,
ent.PalletId AS [ReceivedPallet],
ISNULL(inv.LocationName,'') AS [ActualLoc],
SUM(ISNULL(inv.Qty,0)) AS [LocationQty],
SUM(ISNULL(inv.Qty,0)) AS [TotalQty],
MAX(CAST(ent.ReceiptLineNumber AS INT)) AS [LineNumber],
MAX(ent.WarehouseLotReference) AS [WarehouseLot],
LEFT(SUM(ent.WeightExpected),7) AS [GrossWeight],
LEFT(SUM(inv.[Weight]),7) AS [NetWeight]
FROM WarehouseReceiptDetail AS det
INNER JOIN WarehouseReceiptDetailEntry AS ent
ON det.ReceiptNumber = ent.ReceiptNumber
AND det.FacilityName = ent.FacilityName
AND det.WarehouseName = ent.WarehouseName
AND det.ReceiptLineNumber = ent.ReceiptLineNumber
LEFT OUTER JOIN Inventory AS inv
ON inv.WarehouseName = det.WarehouseName
AND inv.FacilityName = det.FacilityName
AND inv.WarehouseSku = det.WarehouseSku
AND inv.CustomerLotReference = ent.CustomerLotReference
AND inv.LotReferenceOne = det.ReceiptNumber
AND ISNULL(ent.CaseId,'') = ISNULL(inv.CaseId,'')
WHERE
det.WarehouseName = $Warehouse
AND det.FacilityName = $Facility
AND det.ReceiptNumber = #receipt
GROUP BY
ent.PalletId
, ent.WarehouseSku
, inv.LocationName
, inv.Qty
, inv.LotReferenceOne
ORDER BY ent.WarehouseSku
The lines I need partially coalesced are 4 and 5 in the above return.
Create a second dataset with a subquery and join to that subquery - you can extrapolate from the following to apply to your situation:
First the Subquery:
SELECT
WarehouseSku,
SUM(Qty)
FROM
Inventory
GROUP BY
WarehouseSku
Now apply to your query - insert into the FROM clause:
...
LEFT JOIN (
SELECT
WarehouseSKU,
SUM(Qty)
FROM
Inventory
GROUP BY
WarehouseSKU
) AS TotalQty
ON Warehouse.WarehouseSku = TotalQty.WarehouseSku
Without seeing the actual schema DDL it is hard to know the exact cardinality, but I think this will point you in the right direction.

Join Queries with parameter filter on second query SSMS

I have two tables: EQUIPMENT and WORKORDERS.
EQUIPMENT returns the count of Equipment against a particular depot by the type of Equipment:
MAINTDEPOT EQUIPCOUNT EQUIPTYPE
1 44 MC
2 20 MC
3 5 MC
1 20 FS
2 3 FS
3 10 FS
...and so on. These counts rarely change unless a new bit of kit is put in.
I need to join a count of WORKORDERS to this table, but the work orders have a COSTCENTRE of either A B or E. This is so that I can generate a percentage of equipment with workorders.
I've joined the tables, but when I add a parameter filter to the WORKORDERS COSTCENTRE column the Count of EQUIPMENT changes, and I need it to stay the same.
I'm guessing I need to use subqueries to ensure that the left subquery remains static whilst the filter only changes the right hand one. Does anyone have any idea how I do this?
Here's my current query:
SELECT E.E_MAINTDEPOT, E.E_EQUIPCOUNT, C.Category, E.MYORDER, E.W_WORKCOUNT,
E.E_NOWO, E.W_HRS, E.E_QA, E.E_EGI, E.E_CLASS,
ISNULL(ROUND(CAST(E.E_NOWO AS Float) /
CAST(E.E_EQUIPCOUNT AS Float) * 100, 2), 100) AS RESULT,
SUBSTRING(E.E_CLASS, 1, 1) AS EM_CLASS
FROM (
SELECT T.E_MAINTDEPOT, COUNT(T.EQUIP_NO) AS E_EQUIPCOUNT,
SUM(C.W_WORKCOUNT) AS W_WORKCOUNT,
COUNT(T.EQUIP_NO) - SUM(C.W_WORKCOUNT) AS E_NOWO, T.MYORDER,
T.E_QA, T.E_EGI, T.E_CLASS, SUM(C.W_HRS) AS W_HRS
FROM EQDType AS T
FULL OUTER JOIN EquipWOCount AS C
ON T.EQUIP_NO = C.EQUIP_NO
GROUP BY T.MYORDER, T.E_MAINTDEPOT, T.E_QA, T.E_EGI, T.E_CLASS, C.W_FUNCTION
) AS E
INNER JOIN EQDCategory AS C
ON E.MYORDER = C.Myorder
ORDER BY E.MYORDER, E.E_MAINTDEPOT
Thank you

SP Previous year sales data from given date

How to show current year data and previous Data in two column SQL Server 2000
Below Procedure shows my Given date Data I want to set Previous year data from given date in other column
SELECT TOP 100 PERCENT
dbo.SI_Item.ig2_Code, dbo.SI_ItemGroup2.ig2_Desc,
SUM(SI_InvoiceDetail.invcd_Rate * dbo.SI_InvoiceDetail.invcd_Qty -
dbo.SI_InvoiceDetail.invcd_DiscountAmt) AS Total
FROM
dbo.SI_InvoiceDetail
INNER JOIN
dbo.SI_Item ON dbo.SI_InvoiceDetail.itm_ItemCode = dbo.SI_Item.itm_ItemCode
INNER JOIN
dbo.SI_InvoiceMaster ON dbo.SI_InvoiceDetail.invcm_CoCode = dbo.SI_InvoiceMaster.invcm_CoCode AND
dbo.SI_InvoiceDetail.invcm_BrCode = dbo.SI_InvoiceMaster.invcm_BrCode AND
dbo.SI_InvoiceDetail.invcm_SiteCode = dbo.SI_InvoiceMaster.invcm_SiteCode AND
dbo.SI_InvoiceDetail.invcm_Year = dbo.SI_InvoiceMaster.invcm_Year AND
dbo.SI_InvoiceDetail.invcm_Period = dbo.SI_InvoiceMaster.invcm_Period AND
dbo.SI_InvoiceDetail.docs_DocCode = dbo.SI_InvoiceMaster.docs_DocCode AND
dbo.SI_InvoiceDetail.doctyp_Code = dbo.SI_InvoiceMaster.doctyp_Code AND
dbo.SI_InvoiceDetail.invcm_DocNo = dbo.SI_InvoiceMaster.invcm_DocNo
INNER JOIN
dbo.SI_ItemGroup2 ON dbo.SI_Item.ig2_Code = dbo.SI_ItemGroup2.ig2_Code
WHERE (dbo.SI_InvoiceDetail.docs_DocCode = 'inv') AND
(dbo.SI_InvoiceDetail.itm_ItemCode BETWEEN '0101010000001' AND '0301020004001') AND
(dbo.SI_InvoiceMaster.invcm_Date BETWEEN #Invcm_date_from AND #Invcm_date_to)
GROUP BY dbo.SI_Item.ig2_Code ,SI_ItemGroup2.ig2_Desc
Resolved it 70% by changing in Query as below
SELECT TOP 100 PERCENT dbo.SI_Item.ig2_Code, dbo.SI_ItemGroup2.ig2_Desc,year(dbo.SI_InvoiceMaster.invcm_Date) AS SalesYear,
&
Group By Year(dbo.SI_InvoiceMaster.invcm_Date),dbo.SI_Item.ig2_Code ,SI_ItemGroup2.ig2_Desc
ORDER BY Year(dbo.SI_InvoiceMaster.invcm_Date) ,dbo.SI_Item.ig2_Code
but its works but not as i want because its showing year in Row and User mut inpuer date range of aboce 2 years then will show.
if anyone Got Proper solution do share please

Convert SQL query to LINQ to SQL

How do you convert a SQL query with nested SELECT statements to a LINQ statement?
I have the following SQL statement which outputs the results I need but I'm not sure how to replicate this in LINQ .
SELECT X.ITMGEDSC, (SUM(X.[ENDQTY_I]) - SUM(X.[ORDERLINES])) AS AVAIL
FROM SELECT T1.[MANUFACTUREORDER_I],T2.[ITMGEDSC],T1.[ENDQTY_I],
(SELECT (COUNT(VW.[MANUFACTUREORDER_I]) - 1)
FROM [PLCD].dbo.[vw_WIP_Srl] VW
WHERE VW.[MANUFACTUREORDER_I] = T1.[MANUFACTUREORDER_I]
GROUP BY VW.[MANUFACTUREORDER_I]) AS ORDERLINES
FROM [PLCD].dbo.[vw_WIP_Srl] T1
INNER JOIN [PLCD].dbo.IV00101 T2 ON T2.ITEMNMBR = T1.ITEMNMBR
GROUP BY T1 [MANUFACTUREORDER_I],T2.[ITMGEDSC],T1.[ENDQTY_I]) AS X
GROUP BY X.ITMGEDSC
ITEMNMBR is the ID of an item including a revision number, for example A1008001. The last 3 numbers denote the revision. So A1008002 are the same item, just differing revisions. In my query I need to treat these as the same item and output only the quantity for the parent item number (A1008). This parent item number is the column IV00101.ITMGEDSC.
The above code would take the following data
MANUFACTUREORDER_I ITEMNMBR ENDQTY_I
MAN00003140 A1048008 15
MAN00003507 A1048008 1
MAN00004880 A10048001 15
MAN00004880 A10048001 15
MAN00004880 A10048001 15
and output the following results
ITEMNMBR QTY
A1048008 16
A10048001 13*
The reason that this value is 13 and NOT 45 is because they are all part of the same MANUFACTUREORDER_I. In the system this therefore means that there were 15 in stock but two of these have then been transacted out of stock to be used. Hence the 3 rows, one for the goods coming into stock, the other two for two items going out of stock (ignore the quantity in these rows)
As I mentioned at the start, the SQL above gives me the output I'm after but I'm unsure how to replicate this in Linq.
UPDATE - JEFF'S ORIGINAL SOLUTION
var query = from item in db.vw_WIP_Srls
group new { item.MANUFACTUREORDER_I, item.ENDQTY_I } by item.ITEMNMBR into items
select new
{
ItemNumber = items.Key,
QtyAvailable = (from item in items
//assumes quantities equal per order number
group 1 by item into orders
select orders.Key.ENDQTY_I - (orders.Count() - 1))
.Sum()
};
Here you go. Unfortunately I couldn't see the comment you left me anymore but I believe this should be equivalent. I changed the names to match closely with your query.
var query = from a in db.vw_WIP_Srl
join b in db.IV00101 on a.ITEMNMBR equals b.ITEMNMBR
group new { a.MANUFACTUREORDER_I, a.ENDQTY_I } by b.ITMGEDSC into g
select new
{
ITMGEDSC = g.Key,
AVAIL = (from item in g
group 1 by item into orders
select orders.Key.ENDQTY_I - (orders.Count() - 1))
.Sum()
};