I have the following query:
SELECT DISTINCT
T0.DocNum, T0.Status, T1.ItemCode, T2.ItemName,
T1.PlannedQty, T0.PlannedQty AS 'Net Quantity'
FROM
OWOR T0
INNER JOIN
WOR1 T1 ON T0.DocEntry = T1.DocEntry
INNER JOIN
OITM T2 ON T0.ItemCode = T2.ItemCode
WHERE
T0.Status = 'L' AND
T1.ItemCode IN ('BYP/RM/001', 'BYP/RM/002', 'BYP/RM/003', 'BYP/RM/004','BILLET') AND
T2.ItmsGrpCod = 111 AND
(T0.PostDate BETWEEN (SELECT Dateadd(month, Datediff(month, 0, {?EndDate}), 0)) AND {?EndDate})
that returns data like:
Explanation:
To make 10 MM steel bars, billets are used as raw materials. Any ItemCode 'BYP%' is part of solid wastage. The net quantity for every DocNum is the amount of 'MM' steel produced by weight. For example, for DocNum 348, the following are used as inputs:
However for that DocNum, 147.359 of 10 MM steel was produced, meaning the missing 3.52 (150.879 - 147.359) is burned loss (not solid).
How do I modify the query such that for each DocNum, the query returns:
See the SQL code below.
declare #input_tbl table ( doc_num int, item_code varchar(15), item_name varchar(10), planned_qty decimal(15,9), net_qty decimal(15,9) )
declare #ouput_tbl table ( doc_num int, item varchar(15), name varchar(10), quantity decimal(15,9) )
-- Inserting sample data shown by you. You will have to replace this with your 1st query.
insert into #input_tbl values (348, 'BILLET' , '10MM', 154.629000, 147.359000)
insert into #input_tbl values (348, 'BYP/RM/001' , '10MM', -1.008000, 147.359000)
insert into #input_tbl values (348, 'BYP/RM/003' , '10MM', -1.569000, 147.359000)
insert into #input_tbl values (348, 'BYP/RM/004' , '10MM', -1.173000, 147.359000)
-- This stores unique doc numbers from input data
declare #doc_tbl table ( id int identity(1,1), doc_num int )
insert into #doc_tbl select distinct doc_num from #input_tbl
-- Loop through each unique doc number in the input data
declare #doc_ctr int = 1
declare #max_doc_id int = (select max(id) from #doc_tbl)
while #doc_ctr <= #max_doc_id
begin
declare #doc_num int
declare #planned_qty_total decimal(15,9)
declare #net_qty decimal(15,9)
declare #burned_loss decimal(15,9)
declare #item_name varchar(15)
select #doc_num = doc_num from #doc_tbl where id = #doc_ctr
select #planned_qty_total = sum(planned_qty) from #input_tbl where doc_num = #doc_num
select distinct #item_name = item_name, #net_qty = net_qty from #input_tbl where doc_num = #doc_num
select #burned_loss = #planned_qty_total - #net_qty
-- 'Union' is also fine but that won't sort the records as desired
insert into #ouput_tbl select doc_num, item_code, item_name, planned_qty from #input_tbl
insert into #ouput_tbl select #doc_num, 'BurnLoss', #item_name, #burned_loss * -1
insert into #ouput_tbl select #doc_num, 'Net', #item_name, #net_qty
set #doc_ctr = #doc_ctr + 1
end
select * from #ouput_tbl
Ouput:
docnum item name quantity
348 BILLET 10MM 154.629000000
348 BYP/RM/001 10MM -1.008000000
348 BYP/RM/003 10MM -1.569000000
348 BYP/RM/004 10MM -1.173000000
348 BurnLoss 10MM -3.520000000
348 Net 10MM 147.359000000
You should use a UNION. I guess
(/*your original query*/)
UNION
SELECT DISTINCT
T0.DocNum, T0.Status, 'BurnLoss' AS ItemCode, T2.ItemName,
SUM(T1.PlannedQuantity)-T0.PlannedQuantity AS PlannedQuantity, T0.PlannedQuantity AS 'Net Quantity'
FROM
OWOR T0
INNER JOIN
WOR1 T1 ON T0.DocEntry = T1.DocEntry
INNER JOIN
OITM T2 ON T0.ItemCode = T2.ItemCode
WHERE
T0.Status = 'L' AND
T1.ItemCode IN ('BYP/RM/001', 'BYP/RM/002', 'BYP/RM/003', 'BYP/RM/004','BILLET') AND
T2.ItmsGrpCod = 111 AND
(T0.PostDate BETWEEN (SELECT Dateadd(month, Datediff(month, 0, {?EndDate}), 0)) AND {?EndDate})
GROUP BY T0.DocNum
UNION
SELECT DISTINCT
T0.DocNum, T0.Status, 'Net' AS ItemCode, T2.ItemName,
T0.PlannedQuantity, T0.PlannedQuantity AS 'Net Quantity'
FROM
OWOR T0
INNER JOIN
WOR1 T1 ON T0.DocEntry = T1.DocEntry
INNER JOIN
OITM T2 ON T0.ItemCode = T2.ItemCode
WHERE
T0.Status = 'L' AND
T1.ItemCode IN ('BYP/RM/001', 'BYP/RM/002', 'BYP/RM/003', 'BYP/RM/004','BILLET') AND
T2.ItmsGrpCod = 111 AND
(T0.PostDate BETWEEN (SELECT Dateadd(month, Datediff(month, 0, {?EndDate}), 0)) AND {?EndDate})
GROUP BY T0.DocNum
should work, although it might even be better to do some of this in a language like PHP, because now every bit of information is fetched twice (and the query becomes two times as long).
Use a UNION ALL to combine your original query with a second BurnLoss query of GROUP BY T0.DocuNum that computes SUM(T1.PlannedQty) - T0.PlannedQty and a third Net query to show T0.PlannedQty
Related
Dears,
I have an SQL problem. I need to join 2 databases, with 2 tables each. I have the pictures of the tables of the databases here. Thank you very much for your helps.
With a UNION ALL you can get 1 combined resultset from 2 selects.
Then you can group that and SUM the amounts per date.
So you're probably looking for something like this:
select
q.ID,
q.Name,
nullif(sum(case when q.Date = '2018-05-01' then q.Amount end), 0) as "5/1/2018",
nullif(sum(case when q.Date = '2018-05-02' then q.Amount end), 0) as "5/2/2018"
from
(
select u1.ID, u1.Name, a1.Date, a1.Amount
from DB1.Table1 AS u1
join DB1.Table2 AS a1 on (a1.ID = u1.ID and a1.Amount is not null)
where a1.Date IN ('2018-05-01', '2018-05-02')
union all -- combines the results of the 2 selects into one resultset
select u2.ID, u2.Name, a2.Date, a2.Amount
from DB2.Table1 AS u2
join DB2.Table2 AS a2 on (a2.ID = u2.ID and a2.Amount is not null)
where a2.Date IN ('2018-05-01', '2018-05-02')
) AS q
group by q.ID, q.Name
order by q.ID;
An alternative is to JOIN them all up.
select
coalesce(a1.ID, a2.ID) as ID,
max(coalesce(u1.Name, u2.Name)) as Name,
max(case
when coalesce(a1.Date, a2.Date) = '2018-05-01'
and coalesce(a1.Amount, a2.Amount) is not null
then coalesce(a1.Amount, 0) + coalesce(a2.Amount, 0)
end) as "5/1/2018",
max(case
when coalesce(a1.Date, a2.Date) = '2018-05-02'
and coalesce(a1.Amount, a2.Amount) is not null
then coalesce(a1.Amount, 0) + coalesce(a2.Amount, 0)
end) as "5/2/2018"
from DB1.Table2 AS a1
full join DB2.Table2 AS a2 on (a2.ID = a1.ID and a2.Date = a1.Date)
left join DB1.Table1 AS u1 on (u1.ID = a1.ID)
left join DB2.Table1 AS u2 on (u2.ID = a2.ID)
where coalesce(a1.Date, a2.Date) IN ('2018-05-01', '2018-05-02')
group by coalesce(a1.ID, a2.ID)
order by coalesce(a1.ID, a2.ID);
But then note that this way, that there's an assumption that the two Table2 have a uniqueness on (ID, Date)
T-Sql test data:
declare #DB1_Table1 table (id int, Name varchar(30));
declare #DB2_Table1 table (id int, Name varchar(30));
declare #DB1_Table2 table (id int, [Date] date, Amount decimal(8,2));
declare #DB2_Table2 table (id int, [Date] date, Amount decimal(8,2));
insert into #DB1_Table1 (id, Name) values (1,'Susan'),(2,'Juan'),(3,'Tracy'),(4,'Jenny'),(5,'Bill');
insert into #DB2_Table1 (id, Name) values (1,'Susan'),(2,'Juan'),(3,'Tracy'),(4,'Jenny'),(5,'Bill');
insert into #DB1_Table2 (id, [Date], Amount) values
(1,'2018-05-01',20),(2,'2018-05-01',null),(3,'2018-05-01',30),(4,'2018-05-01',50),(5,'2018-05-01',null),
(1,'2018-05-02',15),(2,'2018-05-02',40),(3,'2018-05-02',25),(4,'2018-05-02',8),(5,'2018-05-02',null);
insert into #DB2_Table2 (id, [Date], Amount) values
(1,'2018-05-01',null),(2,'2018-05-01',15),(3,'2018-05-01',20),(4,'2018-05-01',10),(5,'2018-05-01',null),
(1,'2018-05-02',15),(2,'2018-05-02',30),(3,'2018-05-02',35),(4,'2018-05-02',null),(5,'2018-05-02',30);
Using the code below (thank you #BHouse), I am attempting to adjust "ECOMMERCE" selling price to reflect "ENFIELD" selling price. As you can see from results, I am getting multiple entries.
Results can been seen here
SELECT
T1.STRTRADECODE AS [STORE],
T1.LINTITEMNUMBER AS [SKU],
CASE WHEN T1.STRTRADECODE = 'ECOMMERCE' THEN T2.CURNORMALSELL ELSE T1.CURNORMALSELL END AS [SELLINGPRICE]
FROM DAILYSALES T1
LEFT JOIN DAILYSALES T2 ON T1.LINTITEMNUMBER = T2.LINTITEMNUMBER AND T1.STRTRADECODE <> T2.STRTRADECODE
WHERE
T1.DTMTRADEDATE >= '2018-01-02 00:00:00'
AND T1.STRSALETYPE = 'I'
AND T1.STRTRADECODE IN ('ECOMMERCE', 'ENFIELD')
AND T1.LINTITEMNUMBER = '18760'
GROUP BY
T1.STRTRADECODE,
T1.LINTITEMNUMBER,
T1.CURNORMALSELL,
T2.CURNORMALSELL
ORDER BY
T1.STRTRADECODE DESC
Any help will be much appreciated.
Added Sku to the table , matching Sku and different store numbers will retrieve selling value for store2.
This query will help u, to use values matching another store
SELECT T1.STRTRADECODE AS [STORE], T1.LINTITEMNUMBER AS [SKU], T2.CURNORMALSELL AS [SELLINGPRICE]
FROM DAILYSALES T1
INNER JOIN (
SELECT *
FROM DAILYSALES
WHERE name = 'enfield'
) t2
ON t1.sku = t2.sku
WHERE T1.DTMTRADEDATE >= '2018-01-02 00:00:00' AND T1.STRSALETYPE = 'I' AND T1.STRTRADECODE IN (
'ECOMMERCE'
,'ENFIELD'
) AND T1.LINTITEMNUMBER = '18760'
ORDER BY T1.STRTRADECODE DESC
sample:
DECLARE #testtable TABLE (id INT identity(1, 1), name VARCHAR(100), sellingPrice FLOAT, sku BIGINT)
INSERT INTO #testtable (name, sellingPrice, sku)
SELECT 'Enfield', '60.50', '16043853021'
UNION
SELECT 'Ecommerce', '190.50', '16043853021'
UNION
SELECT 'Enfield', '120.45', '06062829018'
UNION
SELECT 'Ecommerce', '180.45', '06062829018'
;
select distinct t.id,t.name,t.sku,t2.sellingPrice
from #testtable t Inner join (select * from #testtable where name = 'enfield') t2
on t.sku = t2.sku
I have 3 tables:
CustomerTypes table
Customers table (has a foreign key CustomerType). A customer can only have one customer type.
CustomersCollection table (contains many customerIds)
The primary SELECT of the query will be on CustomerTypes. I will be selecting two columns: CustomerTypeName and CountInCollection
The CustomerCount column in my query needs to show something like the following:
[Total # of Customers in CustomerType that are in Customer Collection] Of [Total # of Customers in CustomerType]
How can I get the proper customer count of the CustomerType that is part of the collection?
Example:
Customer1, Customer2, and Customer3 are all of CustomerTypeA.
CustomerCollection1 has customers Customer1 and Customer2 in it. The CountInCollection column for the CustomerTypeA record should show '2 of 3'.
Here is how I am able to get each count in separate queries:
-- Total customers in customer collection of customer type
SELECT COUNT(c.Id)
FROM Customer c
INNER JOIN CustomerCollection cc ON c.Id = cc.CustomerId
WHERE cc.CollectionId = 1019 AND c.CustomerTypeId=1000
-- Total customers in customer type
SELECT COUNT(Id) FROM
Customer WHERE CustomerTypeId=1000
Since you are using SQL 2008, I would take advantage of Common Table Expressions, aka CTEs, to assemble the data.
First, we'll need some test data. NOTE: I've thrown in some 'outliers' so that you can see where this kind of logic can bite you later.
DECLARE #CustomerTypes TABLE
(
CustomerTypeID INT,
[Customer Type] VARCHAR(100)
)
INSERT INTO #CustomerTypes
SELECT 1, 'TypeA'
UNION SELECT 2, 'TypeB'
UNION SELECT 3, 'TypeC' --NOTE: An outlier (not in customers-collection)
UNION SELECT 4, 'TypeD' --NOTE: An outlier (not in customers)
DECLARE #Customers TABLE
(
CustomerID INT,
CustomerTypeID INT
)
INSERT INTO #Customers
SELECT 1, 1
UNION SELECT 2, 1
UNION SELECT 3, 1
UNION SELECT 4, 2
UNION SELECT 5, 2
UNION SELECT 6, 2
UNION SELECT 7, 3
DECLARE #CustomersCollection TABLE
(
CollectionID INT IDENTITY(1,1),
CustomerID INT
)
INSERT INTO #CustomersCollection
(CustomerID)
SELECT TOP 2 --INSERT 2 of 3
CustomerID FROM #Customers WHERE CustomerTypeID = 1 --TypeA
INSERT INTO #CustomersCollection
(CustomerID)
SELECT TOP 1 --INSERT 1 of 3
CustomerID FROM #Customers WHERE CustomerTypeID = 2 --TypeB
Second, assemble the CTE data, and generate your output
;WITH CTE_COUNT_TYPE(CustomerTypeID, TypeCount)
AS
(
SELECT CustomerTypeID, COUNT(1)
FROM #Customers
GROUP BY CustomerTypeID
)
--SELECT * FROM CTE_COUNT_TYPE --DEBUG
,
CTE_COUNT_COLLECTION(CustomerTypeID, CollectionCount)
AS
(
SELECT CustomerTypeID, COUNT(1)
FROM #CustomersCollection CC
INNER JOIN #Customers C
ON CC.CustomerID = C.CustomerID
GROUP BY CustomerTypeID
)
--SELECT * FROM CTE_COUNT_COLLECTION --DEBUG
SELECT [Customer Type],
--CONVERT is necessary to combine INT data type (i.e. Count) and VARCHAR data type (i.e. 'as')
CONVERT(VARCHAR(100), COALESCE(CCC.CollectionCount, 0)) +
' of ' +
CONVERT(VARCHAR(100), COALESCE(CCT.TypeCount, 0)) As [Count in Collection]
FROM #CustomerTypes CT
LEFT OUTER JOIN #Customers C --Left outer join assists in outliers
ON CT.CustomerTypeID = C.CustomerTypeID
LEFT OUTER JOIN CTE_COUNT_TYPE CCT --Left outer join assists in outliers
ON CCT.CustomerTypeID = CT.CustomerTypeID
LEFT OUTER JOIN CTE_COUNT_COLLECTION CCC --Left outer join assists in outliers
ON CCC.CustomerTypeID = CT.CustomerTypeID
GROUP BY CT.[Customer Type]
, CCC.CollectionCount
, CCT.TypeCount
Hope so i get the question-
select
ct.CustomerTypeName as [Customer Type],
convert(varchar(30),count(cc.CollectionId)) + ' of ' + convert(varchar(30), count(c.CustomerId)) as [Count in Collection]
from
#Customer c
inner join #CustomerType ct on ct.CustomerTypeId = c.CustomerTypeId
left join #CustomerCollection cc on cc.CustomerId = c.CustomerId
group by
CustomerTypeName
Data script-
declare #customerType table (CustomerTypeId int, CustomerTypeName varchar(100))
insert into #customerType (CustomerTypeId, CustomerTypeName)
select 30, 'TypeA'
union
select 40, 'TypeB'
declare #customer table (CustomerId int, CustomerTypeId int)
insert into #customer (CustomerId, CustomerTypeId)
select 1, 30
union
select 2, 30
union
select 3, 30
union
select 4, 40
union
select 5, 40
union
select 6, 40
declare #customercollection table (CollectionId int, CustomerId int)
insert into #customercollection (CollectionId, CustomerId)
select 100, 1
union
select 200, 2
union
select 300, 5
I'm declaring two comparison dates, I want data from both dates. I'm using left join for combined propose but this is not correct way. I'm missing some data. Instead of left join which one is best for?
result
productid FirstQty SecondQty FirstProductRevenue SecondProductRevenue
COCAK117 1 2 1370.00 1440.00
COCAK632 1 2 1125.00 2250.00
COCAK656 1 NULL 795.00 NULL
COCAK657 1 2 720.00 2090.00
COCAK775 3 1 2475.00 825.00
I'm getting data from full of first table and matching productid from second table, but I want total productid's from both the tables.
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select t1.productid,t1.FirstQty,t2.SecondQty,t1.FirstProductRevenue,t2.SecondProductRevenue
from
(select op.Productid
, count(op.ProductId)as FirstQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t1
----Second duration for all associates-----
left join
(select op.Productid
, count(op.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t2 on t1.productid=t2.productid
END
You can try to get all data at once and then sum only date ranges that you want.
I could made some mistake here as I don't have your data structures.
However you should get the idea how you can implement it.
select op.Productid
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate then
1 else 0 end) FirstQty
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 then
1 else 0 end) SecondQty,
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
then op.Price*op.Quantity
else 0 end),0) as FirstProductRevenue
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
then op.Price*op.Quantity
else 0 end),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where ( Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
Or Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 )
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
Maybe this (simplified):
select coalesce(t1.productid, t2.productid) as productid, t1.FirstQty, t2.SecondQty, t1.FirstProductRevenue, t2.SecondProductRevenue
from
(select ...) t1
----Second duration for all associates-----
full join
(select ...) t2 on t1.productid = t2.productid
try this
you create a function as follows
CREATE FUNCTION OrderDetails (
#StartDate DATETIME,
#EndDate DATETIME
)
RETURNS #tblList TABLE
(
orderId VARCHAR(1000)
)
AS
BEGIN
select orderid
insert into #tblList
from Orderdetails od inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
return
end
then call the function in your stored procedure according to the date you are passing you don't miss any records
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select op1.Productid
, count(op.ProductId)as FirstQty
,count(op1.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
, Round(Sum(op1.Price*op1.Quantity),0) as FirstProductRevenue
from (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate,#EndDate) od on opp.Orderid=od.Orderid ) op
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate1,#EndDate1) od on opp.Orderid=od.Orderid ) op1
-- since 1=1 is always true you will get all data
on 1=1
Group by op.Productid
end
end
This is how my query looks:
DECLARE #month date
DECLARE #CustomerId int
DECLARE #InterfacedSystemId int
SET #month = '2013-05-01'
SET #CustomerId = 24
SET #InterfacedSystemId = 1
SELECT * FROM
(
SELECT CONVERT(BIGINT,MisparHeshbonit) AS PreProcInvoiceNumber ,CONVERT(DATE,TaarichErech,103) AS PreProcDate , ROUND(sum(convert(float,SchumBruto)),2) AS PreProcSum
FROM [VisaCalCredit] VCC
WHERE CONVERT(DATE,TaarichErech,103) BETWEEN #month AND DATEADD(DAY,-1,DATEADD(MONTH,1,#month))
AND VCC.CustomerID = #CustomerID
GROUP BY MisparHeshbonit , CONVERT(DATE,TaarichErech,103)
) AS PreTable
ORDER BY PreProcInvoiceNumber, PreProcDate
SELECT * FROM
(
SELECT InvoiceNumber AS PostProcInvoiceNumber,ActualPaymentTime AS PostProcDate ,ROUND(sum(GrossAmount),2) AS PostProcSum
FROM [CreditAndDebit] C INNER JOIN [Transaction] T ON C.TransactionID = T.ID
WHERE ActualPaymentTime BETWEEN #month AND DATEADD(DAY,-1,DATEADD(MONTH,1,#month))
AND T.CustomerID = #CustomerId
AND T.InterfacedSystemID = 1
GROUP BY InvoiceNumber , ActualPaymentTime
) AS PostTable
ORDER BY PostProcInvoiceNumber ,PostProcDate
I need to find the differences between the PreProcSum and the PostProcSum in those tables - and I cannot make inner join between the inner tables themselves (trigger other problems).
How can I make this inner join between those two tables i've defined in this query?
If your key is (InvoiceNumber, Date), I believe you can do this:
;WITH PreTable AS (
SELECT
CONVERT(BIGINT,MisparHeshbonit) AS PreProcInvoiceNumber,
CONVERT(DATE,TaarichErech,103) AS PreProcDate,
ROUND(sum(convert(float,SchumBruto)),2) AS PreProcSum
FROM [VisaCalCredit] VCC
WHERE
CONVERT(DATE,TaarichErech,103) BETWEEN #month AND DATEADD(DAY,-1,DATEADD(MONTH,1,#month))
AND VCC.CustomerID = #CustomerID
GROUP BY MisparHeshbonit, CONVERT(DATE,TaarichErech,103)
),
PostTable AS (
SELECT
InvoiceNumber AS PostProcInvoiceNumber,
ActualPaymentTime AS PostProcDate,
ROUND(sum(GrossAmount),2) AS PostProcSum
FROM [CreditAndDebit] C INNER JOIN [Transaction] T ON C.TransactionID = T.ID
WHERE ActualPaymentTime BETWEEN #month AND DATEADD(DAY,-1,DATEADD(MONTH,1,#month))
AND T.CustomerID = #CustomerId
AND T.InterfacedSystemID = 1
GROUP BY InvoiceNumber, ActualPaymentTime
),
MergedKeys AS (
SELECT
PreProcInvoiceNumber AS InvoiceNumber,
PreProcDate AS TheDate
FROM PreTable
UNION ALL
SELECT
PostProcInvoiceNumber,
PostProcDate
FROM PostTable
)
SELECT *
FROM
MergedKeys mk
LEFT JOIN PreTable prt
ON prt.PreProcInvoiceNumber = mk.InvoiceNumber
AND prt.PreProcDate= mk.TheDate
LEFT JOIN PostTable pot
ON pot.PostProcInvoiceNumber = mk.InvoiceNumber
AND pot.PostProcDate= mk.TheDate
ORDER BY
mk.InvoiceNumber,
mk.TheDate
Replace LEFT JOIN with JOIN if you are sure you will get all the invoice data in both of your selects.