Opening and Closing Inventory between Dates in SQL Server - sql

I have four tables
tblDate (Date, Year, Month, Day)
tblItems (ItemID, ItemName)
tblItemReceived (Date, ItemID, Quantity)
tblItemUsed (Date, ItemID, Quantity)
I want report with:
Date, ItemName, Opening Quantity, Received Quantity, Used Quantity, Balance
I cannot get the results in date when no receiving.
Tables
Result
i applied, with different table (original)
select *
FROM (SELECT ivt.ITEMID AS rItemID, ivt.NAMEALIAS as rItemName, iUOM, YearRec, MonthRec, OpeningStock, RecMaterial
FROM INVENTTABLE ivt LEFT JOIN
(SELECT in1.YearRec, in1.MonthRec, in1.rItemID, iUOM, ISNULL(in1.OpeningStock, 0) AS OpeningStock, ISNULL(in1.ReceivedMaterial,0) AS RecMaterial
FROM (SELECT Year(ReceivedDate) AS YearRec, Month(ReceivedDate) AS MonthRec, rItemID, iUOM, MIN(OpenQty) AS OpeningStock, SUM(RecQty) ReceivedMaterial
FROM ( SELECT rItemID, ReceivedDate, iUOM, SUM(ReceivedQty) AS RecQty, (SELECT SUM(q.QTY) FROM VENDPACKINGSLIPTRANS q WHERE q.INVENTDATE < rm.ReceivedDate AND q.ITEMID = rm.rItemID) AS OpenQty
FROM ( SELECT vp.ITEMID AS rItemID, vp.INVENTDATE as ReceivedDate, vp.PURCHUNIT as iUOM, SUM(vp.QTY) as ReceivedQty FROM VENDPACKINGSLIPTRANS AS vp GROUP BY vp.ITEMID, vp.INVENTDATE,vp.PURCHUNIT) rm
GROUP BY rItemID, ReceivedDate,iUOM) inv
GROUP BY Year(ReceivedDate), Month(ReceivedDate), rItemID, iUOM) in1 WHERE (in1.YearRec= 2016 AND in1.MonthRec = 06)
) iv2
ON ivt.ITEMID = iv2.rITemID) le
LEFT JOIN
(SELECT c1.YearConsume, c1.MonthConsume, c1.cItemID, c1.BOM_Unit, MIN(c1.BOM_Consumption_Prev) as PrevConsump, SUM(c1.BOM_ConsumptionQty_Curr) AS TotalConsump
FROM ( SELECT Year(DateConsume) AS YearConsume, Month(DateConsume) AS MonthConsume, ItemID as cITemID, BOM_Unit, ISNULL(BOM_Consumption_Open,0) AS BOM_Consumption_Prev, SUM(BOM_ConsumptionQty) AS BOM_ConsumptionQty_Curr
FROM ( SELECT DateConsume, ItemID, BOM_Unit, SUM(BOM_Consumption) AS BOM_ConsumptionQty,
( SELECT SUM(bc.BOM_Consumption) FROM (SELECT (b.TRANSDATE) AS DateConsume, b.ITEMID AS cItemID, b.BOMUNITID BOM_Unit, SUM(b.BOMCONSUMP) AS BOM_Consumption FROM PRODJOURNALBOM b GROUP BY b.TRANSDATE, b.ITEMID, b.BOMUNITID) bc
WHERE (bc.DateConsume < aa.DateConsume) AND bc.cItemID = aa.ItemID) AS BOM_Consumption_Open
FROM (SELECT (b.TRANSDATE) AS DateConsume, b.ITEMID AS ItemID, b.BOMUNITID BOM_Unit, SUM(b.BOMCONSUMP) AS BOM_Consumption FROM PRODJOURNALBOM b GROUP BY b.TRANSDATE, b.ITEMID, b.BOMUNITID) aa
GROUP BY DateConsume, ItemID, BOM_Unit) cc
GROUP BY Year(DateConsume), Month(DateConsume), ItemID,BOM_Unit, BOM_Consumption_Open) c1
WHERE (YearConsume= 2016 AND MonthConsume = 06)
GROUP BY c1.YearConsume, c1.MonthConsume, c1.cItemID, c1.BOM_Unit) rt
ON le.rItemID = rt.cITemID
WHERE le.rITEMID IN ('FML-RM006', 'FML-RM008','FML-RM016','FML-RM018')

Related

Update from table A to table B on ORACLE

How to update set QTY = balanceqty
sql
SELECT
balanceid,
balanceqty,
id,
qty
FROM
(
SELECT
lotxlocxid.id balanceid,
SUM(lotxlocxid.qty) balanceqty,
lotxlocxid.status AS balancestatus,
id.id,
id.qty,
id.status
FROM
wmwhse1.lotxlocxid left
JOIN (
SELECT
id.id,
SUM(id.qty) AS qty,
id.status
FROM
wmwhse1.id
GROUP BY
id.id,
id.status
ORDER BY
id.id
) id ON lotxlocxid.id = id.id
WHERE
lotxlocxid.qty > 0
GROUP BY
lotxlocxid.id,
lotxlocxid.status,
id.id,
id.qty,
id.status
ORDER BY
lotxlocxid.id
)
WHERE
balanceqty - qty != '0'
enter image description here
You can use merge statement to update qty column from wmwhse1.id table like below.
merge into wmwhse1.id tgt
using(
SELECT
balanceid,
balanceqty,
id,
qty
FROM
(
SELECT
lotxlocxid.id balanceid,
SUM(lotxlocxid.qty) balanceqty,
lotxlocxid.status AS balancestatus,
id.id,
id.qty,
id.status
FROM
wmwhse1.lotxlocxid left
JOIN (
SELECT
id.id,
SUM(id.qty) AS qty,
id.status
FROM
wmwhse1.id
GROUP BY
id.id,
id.status
ORDER BY
id.id
) id ON lotxlocxid.id = id.id
WHERE
lotxlocxid.qty > 0
GROUP BY
lotxlocxid.id,
lotxlocxid.status,
id.id,
id.qty,
id.status
ORDER BY
lotxlocxid.id
)
WHERE
balanceqty - qty != '0'
)src
on(tgt.id = src.id)
when matched then update set tgt.qty = src.balanceqty
where tgt.qty = src.qty
;

Top 20 Count of SKUs per Store

I am trying to create a query that pulls down the top 20 out of stock SKUs per store. Here is what I have so far:
;with top20OOS as
(select wi.SKU
, count(wi.SKU) OOSCount
, wi.ProductId
, wi.PseudoStoreId
from WaveItem wi (nolock)
where wi.isOutOfStock = 1
and DateAdded between '2018-01-01' and '2018-05-31'
group by wi.SKU, p.ProductName, wi.ProductId, bo.brandname, p.size, mo.name,
wi.PseudoStoreId
)
select oos.SKU
, oos.ProductName
, oos.OOSCount
, s.StoreName
, s.StoreID from top20OOS oos
join WaveItem wi (nolock) on wi.ProductId = oos.ProductId
and wi.PseudoStoreId = oos.PseudoStoreId
join tblStore s (nolock) on s.PseudoStoreID = wi.PseudoStoreId
where s.StoreID in (1094,1088)
and DateAdded between '2018-01-01' and '2018-05-31'
group by oos.SKU, oos.ProductName, s.StoreName, s.StoreID, oos.OOSCount
order by s.StoreName asc, OOSCount desc
This just pulls all of the out of stock SKUs for stores 1094 and 1088, and I need to limit it to the top 20 per store. I am using SQL Server 2017
It's a bit verbose because I can't remember if ROW_NUMBER() plays well with Group By in the same query so I erred on the side of caution and broke it apart into separate subqueries.
;with top20OOS as
(select wi.SKU
, count(wi.SKU) OOSCount
, wi.ProductId
, wi.PseudoStoreId
from WaveItem wi (nolock)
where wi.isOutOfStock = 1
and DateAdded between '2018-01-01' and '2018-05-31'
group by wi.SKU, p.ProductName, wi.ProductId, bo.brandname, p.size, mo.name,
wi.PseudoStoreId
)
SELECT sku,
productName,
OOSCount,
StoreName,
StoreID
FROM (SELECT sku,
productName,
OOSCount,
StoreName,
StoreID,
ROW_NUMBER() OVER
( PARTITION BY StoreID
ORDER BY OOSCount
) AS rn
FROM (select oos.SKU
, oos.ProductName
, oos.OOSCount
, s.StoreName
, s.StoreID from top20OOS oos
join WaveItem wi (nolock) on wi.ProductId = oos.ProductId
and wi.PseudoStoreId = oos.PseudoStoreId
join tblStore s (nolock) on s.PseudoStoreID = wi.PseudoStoreId
where s.StoreID in (1094,1088)
and DateAdded between '2018-01-01' and '2018-05-31'
group by oos.SKU, oos.ProductName, s.StoreName, s.StoreID, oos.OOSCount
) TMP
) TMP2
WHERE rn <= 20;

Selection within table for new column

I have the table pricedata (see attached file). I want to add two extra columns to this table (MinPrice of Competitor and CompetitorID of MinPrice). I wrote a code to get the column MinPrice of Competitor, BUT I have no idea how to get second column, any help ????
Code:
select a.ValuationDate, a.shop, a.Itemcode, a.OwnPrice,
a.[sales price competitor], a.[competitor ID], b.MinPrice
from [PriceTable] a
inner join
(select ValuationDate, Shop, ItemCode,
min([sales price competitor]) as MinPrice
FROM [PriceTable]
group by ValuationDate, Shop, ItemCode) b
on a.ValuationDate = b.ValuationDate
and a.Shop = b.Shop
and a.ItemCode = b.ItemCode
Actual Table:
Required Table:
Here you go. Hope this helps.
select
a.ValuationDate,
a.shop
a.Itemcode,
a.OwnPrice,
a.[sales price competitor],
a.[competitor ID],
b.MinPrice ,
MINCOMPID.[competitor ID] AS 'CompetitorID of MinPrice'
from [PriceTable] a
inner join
(
select ValuationDate, Shop, ItemCode, min([sales price competitor]) as MinPrice FROM [PriceTable]
group by ValuationDate, Shop, ItemCode
) b
on a.ValuationDate=b.ValuationDate and a.Shop=b.Shop and a.ItemCode=b.ItemCode
INNER JOIN [PriceTable] AS MINCOMPID
ON MINCOMPID.ValuationDate=b.ValuationDate and MINCOMPID.Shop=b.Shop and MINCOMPID.ItemCode=b.ItemCode AND MINCOMPID.[sales price competitor]=b.MinPrice
Look at (not tested). A common way to get the row with min/max value is SELECT TOP(1) .. ORDER BY .. DESC/ASC
select a.ValuationDate, a.shop, a.Itemcode, a.OwnPrice,
a.[sales price competitor], a.[competitor ID],
c.MinPrice, c.[competitor ID]
from [PriceTable] a
cross apply
(SELECT TOP(1) b.[competitor ID]
b.[sales price competitor] as MinPrice
FROM [PriceTable] b
WHERE a.ValuationDate = b.ValuationDate
and a.Shop = b.Shop
and a.ItemCode = b.ItemCode
ORDER BY b.[sales price competitor] DESC) c

Including CTE within a query

I have the following code which works perfectly.
What I need to do is include it in a query using the result of the CTE as a column in the query result but I cannot work out the way to include it.
Any ideas please?
What I would like is effectively this:
select a,
b,
c,
d,
WITH invoicedates AS (
SELECT
ROW_NUMBER() OVER (ORDER BY Inv_Date DESC) AS RowNumber,
inv_Date, INVIT_PARTNO
FROM Invoices join InvoiceItems on invit_invno = inv_no
WHERE invit_partno = stock_no and inv_canind <> 'Y' and inv_date >= DATEADD(yy, -1, getdate())
)
SELECT
AVG(DATEDIFF(DD, O2.Inv_Date, O1.Inv_Date)) AS AverageFrequency
FROM invoicedates O1
LEFT JOIN invoicedates O2
ON O2.RowNumber = O1.RowNumber + 1
from stock where ..........
to give a resulting output of a b c d result
You should be able to just reorder how you're using the CTE:
; WITH invoicedates (RowNumber, inv_Date, INVIT_PARTNO) AS (
SELECT
ROW_NUMBER() OVER (ORDER BY Inv_Date DESC) AS RowNumber,
inv_Date, INVIT_PARTNO
FROM Invoices join InvoiceItems on invit_invno = inv_no
WHERE invit_partno = stock_no and inv_canind <> 'Y' and inv_date >= DATEADD(yy, -1, getdate())
)
select a,
b,
c,
d,
AVG(DATEDIFF(DD, O2.Inv_Date, O1.Inv_Date)) AS AverageFrequency
FROM invoicedates O1
LEFT JOIN invoicedates O2
ON O2.RowNumber = O1.RowNumber + 1

search between date with query have calculation and counter

Hello everyone i have big query to calculation and counter by clinic ID
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService, SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept
FROM ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc WHERE (Status = 1)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write) AS cr ON
cs.ID = cr.Clinic_Service_ID INNER JOIN
(SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name) AS nc ON cs.Clinic_ID = c.ID
GROUP BY nc.Name, nc.ID
it is true query but i want add between date
AND tc.Date_Write BETWEEN tc.Date_Write AND tc.Date_Write
in subquery
Select tc.Date_Write
Group by tc.Date_Write
in main query
like this
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE (Status = 1) AND tc.Date_Write BETWEEN tc.Date_Write AND tc.Date_Write
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
it is false query why because it is display every receipt but i want display
1 - TotalPriceService
2 - TotalPaid
3 - TotalInsurance
4 - TotalCounterReceipt
5 - FromDate
6 - ToDate
the true query that returns calculation and counter i want add search by date i know the second query it is wrong but i want search by date BETWEEN tc.Date_Write FROMDATE AND TODATE how do this thank you for help me
Your BETWEEN clause checks whether a date is between itself. This will return true for every record.
To use BETWEEN correctly, you need to supply two other dates. This query seems like a candidate for a stored procedure that has two date parameters, a "from" date and a "to" date, like this:
CREATE PROCEDURE usp_GetClinicStats(
#FromDate DATETIME,
#ToDate DATETIME
)
AS
BEGIN
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE Status = 1
AND tc.Date_Write BETWEEN CONVERT(VARCHAR, #FromDate, 111) AND CONVERT(VARCHAR, #ToDate, 111)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
END
CREATE PROCEDURE usp_GetClinicStats(
#FromDate DATETIME,
#ToDate DATETIME
)
AS
BEGIN
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE (Status = 1) AND convert(varchar,tc.Date_Write,111) BETWEEN
convert(varchar,#FromDate,111) AND convert(varchar,#ToDate,111)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
END