Two Identical non relation table compare and give result in row data - sql-server

I have two Identical table with different purpose each.
Table A
ID,TypeofAsset, Amount
1,C,300
2,A,40
3,F,90
Table B
ID,TypeofAsset,amount
1,G,500
2,A,20
3,C,150
Result with Query (Table A id= 1 compare with Table B ID =3)
Col, Result
TypeofAsset, match -- (C)
Amount, 150 --(Absolute value of Amount difference)
Any help will be appreciate.
Thanks

You can do a JOIN on TypeofAsset column like
select t1.TypeofAsset,
case when t1.Amount > t2.Amount then t1.Amount - t2.Amount
else t2.Amount - t1.Amount end as diff_amount
from tablea t1 join tableb t2 on t1.TypeofAsset = t2.TypeofAsset;
You can as well use ABS() function as commented like
select t1.TypeofAsset,
ABS(t1.Amount - t2.Amount) as diff_amount
from tablea t1 join tableb t2 on t1.TypeofAsset = t2.TypeofAsset;

Related

Incorrect Sum On Table Join

I am writing a query but i'm getting wrong result.Table are follows:
Tbl1(ProId, price,VId)
Tbl2(ProId, price, VId)
I have written this query:
SELECT
a.ProId, b.ProId,
SUM(a.price) - SUM(b.price) AS TotalPro
FROM
tbl1 AS a
INNER JOIN
tbl2 AS b ON a.ProId = b.ProId
WHERE
a.VId = '1234'
GROUP BY
a.ProId, b.ProId;
This query is returning an incorrect answer. What I have done is sum the price from table one and two separately and minus them the answer was fine. But when I join, I don't know why I am getting the wrong answer. ProId is same in both table, values are same.
I guess you want sth like below:
SELECT ProdId, SUM(price)
FROM (
SELECT a.ProId,a.price
FROM Tbl1 a
WHERE a.VId='1234'
UNION ALL
SELECT b.ProdId, -b.price
FROM Tbl2 b
--WHERE b.VId ='1234' (?)
) sub
GROUP BY ProdId;
The issue with JOIN is you may have some rows that are summed multiple times.

Getting more than two counts in one query

scenario: I have table A and Table B. Both have the primary key of Rep_time_frame. We replicate data by terms. however, that process at times was repeated.
task: Match the source counts with the destination table counts.
problem: I can match the rows of the source table but not the destination table because the replication for some terms happened twice. So, my counts are off.
SELECT d.REPT_TIME_FRAME,
c.SOURCE_TOTAL_RECORDS,
COUNT(*) TOTAL_RECORDS,
CASE
WHEN COUNT(*) > c.SOURCE_TOTAL_RECORDS THEN c.SOURCE_TOTAL_RECORDS
ELSE COUNT(*)
END FINAL_TOTAL_RECORDS,
***CASE
WHEN EXISTS (SELECT REPT_TIME_FRAME
FROM TableA_Counts
WHERE REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY REPT_TIME_FRAME
HAVING COUNT(*) > 1) THEN 'UPLOADED MORE THAN ONCE'
ELSE'UPLOADED ONCE'
END NUMBER_OF_REPLICATIONS***
FROM TableA d
INNER JOIN TableA_Counts c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
WHERE d.REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY d.REPT_TIME_FRAME, c.SOURCE_TOTAL_RECORDS```
please note that the bolded area, when ran returns for the newly made column Number_of_replications "Uploaded More than once" on all counts. For the purposes of this example. Here are the facts.
201705 was replicated 2X
201801 once and 201708 once.
expected result. I want to have 201705 'Uploaded more than once', and the rest 201801 and 201708 'Uploaded Once'
Does this help?
http://sqlfiddle.com/#!18/8692a/1
I always try and get the counts then do a case statement on the final figures. I've based that SqlFiddle on the notion that TableA_Counts is the table with more than one entry for 201705. Is that correct?
CREATE TABLE TableA (REPT_TIME_FRAME int)
INSERT INTO TableA(REPT_TIME_FRAME)VALUES
(201705),
(201708),
(201801),
(201706),
(201710),
(201803 )
CREATE TABLE TableA_Counts (REPT_TIME_FRAME int)
INSERT INTO TableA_Counts(REPT_TIME_FRAME)VALUES
(201705),
(201708),
(201705),
(201801),
(201706),
(201710),
(201803)
SELECT
d.REPT_TIME_FRAME,count(*) as TOTAL_RECORDS,SOURCE_TOTAL_RECORDS,
CASE WHEN SOURCE_TOTAL_RECORDS > 1 then 'more than' else 'just one' end as NUMBER_OF_REPLICATIONS
FROM
TableA d
LEFT JOIN
(SELECT REPT_TIME_FRAME ,count(*) as SOURCE_TOTAL_RECORDS from TableA_Counts group by REPT_TIME_FRAME) c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
group by d.REPT_TIME_FRAME,SOURCE_TOTAL_RECORDS
SELECT d.REPT_TIME_FRAME,
c.SOURCE_TOTAL_RECORDS,
COUNT(*) TOTAL_RECORDS,
CASE
WHEN COUNT(*) > c.SOURCE_TOTAL_RECORDS THEN c.SOURCE_TOTAL_RECORDS
ELSE COUNT(*)
END FINAL_TOTAL_RECORDS,
a.count AS NUM_OF_REPLICATIONS
FROM TableA d
INNER JOIN TableACounts c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
INNER JOIN (SELECT REPT_TIME_FRAME ,count(REPT_TIME_FRAME) as count
FROM TableAcounts
WHERE REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY REPT_TIME_FRAME) AS a ON (a.REPT_TIME_FRAME = d.REPT_TIME_FRAME)
WHERE d.REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY d.REPT_TIME_FRAME, c.SOURCE_TOTAL_RECORDS, a.count

sql server - How to Get all distinct value in group by column from two table and count from another table for each value

I have 3 tables in that 2 tables are master table and 3rd is transaction table. i need to get count from transaction table for each value in other two table without loosing rows in mater table
i need result like below
Table layout for understanding
This is the code i have tried,
select s.status_name, e.machine_group_name, qty = COALESCE(COUNT(e.id),0)
from tbl_status s
left outer JOIN tbl_transaction as e ON e.status_name = s.status_name
group by e.machine_group_name, s.status_name
This is solution i have figured:
select m.machine_group_name, s.status_name, qty = COUNT(e.id) from
tbl_machine_group as m
cross join tbl_status as s
left outer join tbl_transaction as e on e.status_name = s.status_name
and e.machine_group_name = m.machine_group_name
group by m.machine_group_name, s.status_name
order by machine_group_name
select
MC_Group_Name
,Status_Name
,count(1) as [Count of Transaction]
from
tbl_Transaction tbl_3
left join tbl_Machine_Group tbl_1
on tbl_3.MC_Group_Name = tbl_1.MC_Group_Name
left join tbl_Status tbl_2
on tbl_3.Status_Name = tbl_2.Status_Name
group by
MC_Group_Name
,Status_Name

Return other columns corresponding to one column minimum

Please someone help with this query:
Query table1 and return all table1.parentOrderNumber, table1.orderPriority, table1.orderQuantity values where the corresponding table2.orderNumber equals table1.parentOrderNumber and the lowest value table2.operationNumber has an table2.scheduledStartDate greater than or equal to the current date -5 days and less than or equal to the current date + 3 days.
Here table2 has duplicate orderNumber which have different operationNumber against them. I have tried having clause and others but it doesnt seem to help. I have written following query so far which is returning duplicate parentOrderNumber and not only for minimum value of operationNumber:
SELECT
t1.parentOrderNumber AS parentOrderNumber
,t2.scheduledStartDate AS scheduledStartDate
,t1.salesOrderNumber AS salesOrderNumber
,t1.salesOrderLine AS salesOrderLine
,t1.orderPriority AS orderPriority
,t1.orderQuantity AS orderQuantity
,t1.modelNumber AS modelNumber
,t2.calculatedActualLabor AS CalculatedActualLabor
,MIN(t2.operationNumber) AS operationNumber
FROM
table2 t2 WITH(NOLOCK)
LEFT JOIN
table1 t1 WITH(NOLOCK) ON t2.orderNumber = t1.parentorderNumber
WHERE
parentOrderNumber <> ''
AND t1.productionplant = 'xyz'
GROUP BY
--t1.orderNumber
t1.parentOrderNumber
,t2.scheduledStartDate
,t1.salesOrderNumber
,t1.salesOrderLine
,t1.orderPriority
,t1.orderQuantity
,t1.modelNumber
,t2.calculatedActualLabor
If I'm understanding your question properly the following query should get you what you want:
select * from t2 inner join
(select t2.ordernumber, min(t2.operationnumber) as operationnumber
from t2 where t2.schedulestartdate between getdate()-5 and getdate()+3
group by ordernumber) t2_1
on t2.ordernumber = t2_1.ordernumber and t2.operationnumber = t2_1.operationnumber
inner join t1 on t1.parentordernumber = t2.ordernumber

Display common values in two tables that are not present in the third table

The three tables in question are:
Table A - relevant columns are TimeTicket and IdAddress
Table B - relevant columns are CommunicationNumber, TimeCreate and IdAddress.
Table C - relevant columns are CommunicationNumber, LastCalled, NextCall
Table C is created by a join of TableA and TableB on IdAddress
INSERT INTO tblC ([CommunicationNumber], [LastCalled] ,[NextCall])
SELECT T2.CommunicationNumber, T2.TimeCreate, T1.TimeTicket
FROM tblA T1
INNER JOIN tblB T2
ON T1.IdAddress = T2.IdAddress AND T2.CommunicationNumber IS NOT NULL
That's one part of the process, and that's fine.
Now, when there is new data in Table A and Table B, I want to update the data entries in Table C. However, I want to ignore the values from Table A and Table B that I have already entered into Table C.
To achieve this, I used NOT EXISTS and wrote a query that looks like this.
INSERT INTO tblC ([CommunicationNumber], [LastCalled] ,[NextCall])
SELECT T2.CommunicationNumber, T2.TimeCreate, T1.TimeTicket
FROM tblA T1
INNER JOIN tblB T2
ON T1.IdAddress = T2.IdAddress AND T2.CommunicationNumber IS NOT NULL
WHERE NOT EXISTS (SELECT T3.CommunicationNumber
FROM [dbo].[tblPhoneLogRep] T3
WHERE T1.TimeTicket <> T3.NextCall AND T2.TimeCreate <> T3.LastCalled AND T2.CommunicationNumber <> T3.CommunicationNumber)
However, this query always returns an empty set.
Could someone please explain to me what is it that I am doing incorrectly?
Try using the EXCEPT set operator:
INSERT INTO tblC ([CommunicationNumber], [LastCalled] ,[NextCall])
SELECT T2.CommunicationNumber, T2.TimeCreate, T1.TimeTicket
FROM tblA T1
INNER JOIN tblB T2
ON T1.IdAddress = T2.IdAddress AND T2.CommunicationNumber IS NOT NULL
EXCEPT
SELECT CommunicationNumber, LastCalled, NextCall FROM tblC
To fix your existing query, you would need to change your <> operators to = operators, like so:
INSERT INTO tblC ([CommunicationNumber], [LastCalled] ,[NextCall])
SELECT T2.CommunicationNumber, T2.TimeCreate, T1.TimeTicket
FROM tblA T1
INNER JOIN tblB T2
ON T1.IdAddress = T2.IdAddress AND T2.CommunicationNumber IS NOT NULL
WHERE NOT EXISTS (SELECT 1
FROM tblC
WHERE T1.TimeTicket = tblC.NextCall AND T2.TimeCreate = tblC.LastCalled AND T2.CommunicationNumber = tblC.CommunicationNumber)
Personally, I think the EXCEPT syntax is more clear though.
Your issue is that you are essentially using a double negative. You are saying NOT EXISTS and you are setting your WHERE criteria to <>. I think it would work out if you either used EXISTS or change you criteria =.

Resources