How to extract from two tables and join them like the example - sql

Table A ............................. Table B
+-----------+ .........................+-----------+
|Id | Sum1| .........................|Id |Sum2 |
| 1 | 1500 | .........................| 1 | 2300|
| 1 | 2500 | .........................| 1 | 1500|
| 1 | 1300 | .........................+-----------+
+-----------+
I have Table A and Table B. I need query to result like this:
Result
+-----------------------+
|Id | Sum1| |Sum2 |
| 1 | 1500 | |......0|
| 1 | 2500 | |......0|
| 1 | 1300 | |......0|
| 1 | 0....| | 2300 |
| 1 | 0....| | 1500 |
+-----------------------+
I need to filter with id and the result should be like the third table where I can divide left and right column from Table A and Table B.
Please help. I tried with other examples but I didn't succeed.

If you want that output, you can use:
SELECT ID, Sum1, 0 AS Sum2
FROM TableA
UNION ALL
SELECT ID, 0 AS Sum1, Sum2
FROM TableB
Not sure why it would be a useful resultset, though ...

Related

How to write a sql script that cursors through a table and inserts into a different table

I am new to sql server i have the following table structure that contains more than a thousand rows.
But for example purposes this is what it would look like
Table Import
+------+---------+------------+------------+------------+------------+------------+
| Name | Code | SocksTotal | GlovesTotal| JeansTotal | ShirtsTotal| shoesTotal |
+------+---------+------------+------------+------------+------------+------------+
| OT | 45612 | 2 | 1 | 0 | 1 | 4 |
| OT | 1234 | 0 | 1 | 0 | 0 | 0 |
| US | 45896| 0 | 0 | 0 | 0 | 0 |
+------+---------+------------+------------+------------+------------+------------+
and a second table called Items follows
+------+---------+
| ID | Item |
+------+---------+
| 1 | socks |
| 2 | Gloves|
| 3 | Jeans |
| 4 | Shirts|
| 5 | shoes |
+------+---------+
from the above tables i need to write a script that would be inserted into a different table called ImportItems_Summary.
the expected output is
+------+---------+------------+------------+
| Id | Code | Items_id |Import_total|
+------+---------+------------+------------+
| 1 | 45612 | 1 | 2 |
| 2 | 45612 | 2 | 1 |
| 3 | 45612 | 4 | 1 |
| 4 | 45612 | 5 | 4 |
| 5 | 1234 | 2 | 1 |
+------+---------+------------+------------+
as you can see here that code 45612 now has 4 entries into the ImportItems_summary table where the items is not equal to 0 and the Items_id is linked to the Items table ID column.
How can i achieve the above output?.. I read up and saw a cursor might help but i am not sure how to implement this
One method uses cross apply to unpivot the columns of the unnormalized table to rows, then brings the items table with a join, and finally inserts in the target table:
insert into ImportItems_Summary (code, items_id, import_total)
select im.code, it.items_id, x.import_total
from import im
cross apply (values
('socks', sockstotal),
('gloves', glovestotal),
('jeans', jeanstotal),
('shirts', shirtstotal),
('shoes', shoestotal)
) x(item, import_total)
inner join items it on it.item = x.item

How can I update every fields data when remove rows

I'm looking for an way to update some rows right after I deleted some rows on MariaDB.
For examples, my talbes are look like:
--------------------------------------
| main_id | name | value | sub_id |
--------------------------------------
| 1 | DRINKS | 1000 | COKE |
| 1 | DRINKS | 2000 | BEER |
| 1 | DRINKS | 0600 | WATER |
| 2 | SALAD | 2000 | Peanut |
| 3 | BREADS | 1500 | FLAT |
| 3 | BREADS | 1000 | TOAST |
| 4 | BEEF | 3000 | SAUSAGE|
...
When I remove '2' SALAD, I want to update every rows main_id to main_id-1 like
--------------------------------------
| main_id | name | value | sub_id |
--------------------------------------
| 1 | DRINKS | 1000 | COKE |
| 1 | DRINKS | 2000 | BEER |
| 1 | DRINKS | 0600 | WATER |
| 2 | BREADS | 1500 | FLAT |
| 2 | BREADS | 1000 | TOAST |
| 3 | BEEF | 3000 | SAUSAGE|
...
// | 2 | SALAD | 2000 | Peanut | has removed so every main_id updated.
I cannot use PRIMARY KEY, because the things are so many duplicated.
If I have to join every rows, then I'm worried about performance, so I cannot find the way to solve the problem.
Thanks for your help.
After the Delete statement :
DELETE FROM t WHERE main_id = 2;
an Update statement containing Analytic Functions might be issued provided your DB version is 10.2+ :
UPDATE t
JOIN (WITH t2 AS
(
SELECT LAG(main_id,1) OVER (ORDER BY main_id) AS lg, t.*
FROM t
)
SELECT t2.*,
1 + SUM(CASE WHEN COALESCE(lg,main_id) = main_id THEN 0 ELSE 1 END )
OVER (ORDER BY main_id) AS new_id
FROM t2 ) t2
ON t.main_id = t2.main_id
SET t.main_id = t2.new_id;
to get main_id - 1 is updated for main_id column for main_id >2 for this individual case.
A Delete Trigger containing an Update cannot be applied on the same because of mutating trigger problem.
Demo

How can I compare 2 tables in MS-SQL?

How can I compare 2 tables with the same rows, but different data?
The tables are something like this:
1. Table price_old:
|-----------------------|
| id | price1 | price2 |
|-----------------------|
| 1 | 12 | 12 |
|-----------------------|
| 2 | 12 | 55 |
------------------------|
| 3 | 12 | 40 |
-------------------------
The tables are something like this:
2. Table price_old:
|-----------------------|
| id | price1 | price2 |
|-----------------------|
| 1 | 12 | 12 |
|-----------------------|
| 2 | 13 | 40 |
------------------------|
| 3 | 10 | 40 |
-------------------------
The Result should look like this:
3. Table Result:
|----------------------------------------------------------|
| id | price1_old | price1_new | price2_old | price2_new |
|----------------------------------------------------------|
| 2 | 12 | 13 | 55 | 40 |
|----------------------------------------------------------|
| 3 | 13 | 10 | 40 | 40 |
Try this, joining on the id and filtering out occurrences where at least one price is different:
SELECT
old.id,
old.price1 as price1_old,
old.price2 as price2_old,
new.price1 as price1_new,
new.price2 as price2_new
FROM price_old as old
LEFT JOIN price_new as new on old.id=new.id
WHERE old.price1<>new.price1
OR old.price2<>new.price2
This is might be an approach:
SELECT 'TableName' AS `set`, r.*
FROM robot r
WHERE ROW(r.col1, r.col2, …) NOT IN
(
SELECT *
FROM TableName2
)
UNION ALL
SELECT 'TableName2' AS `set`, t.*
FROM tbd_robot t
WHERE ROW(t.col1, t.col2, …) NOT IN
(
SELECT *
FROM TableName1
)

Create a combined list from two tables

I have a table with CostCenter_ID (int) and a second table with Process_ID (int).
I'd like to combine the results of both tables so that each cost center ID is assigned to all process IDs, like so:
|CostCenterID | ProcessID |
---------------------------
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
I've done it before but I'm drawing a blank. I've tried this:
SELECT CostCenter_ID,NULL FROM dbo.Cost_Centers
UNION ALL
SELECT NULL,Process_ID FROM dbo.Processes
which returns this:
|CostCenterID | ProcessID |
---------------------------
| 1 | NULL |
| NULL | 1 |
| NULL | 2 |
| NULL | 3 |
Try:
select a.CostCenterID, b.ProcessID
from table1 a
cross join table2 b
or:
select a.CostCenterID, b.ProcessID
from table1 a
,table2 b
NB: cross join is the better method as it makes it clearer to the reader what your intentions are.
More info (with pics) here: http://www.w3resource.com/sql/joins/cross-join.php

Query for data in two tables connected by a third. Data Sometimes only on one

I thought I could figure this out but I am having a lot of issues.I have 3 Tables, Table1, Table2, and Table3. These tables where designed by someone else and I have to work with them. They were not designed to be used the way they are used today.
The bottom line is I need to be able to enter an Item_No, this will always exist in Table2. And if the Item_No can also be found in Table 3, could be multiple times or none, and there can be times where I can find it 5 times in Table2 and only 3 times in Table3. If it is in Table3 it will also be in Table1.
So, using the Item_No i can find on Table2, return the Order_qty's associated with those rows. Then using the if exist getting Table1.ID where Table1.ID = Table3.ID WHERE Table3.Item_No = Table2.Item_No
I came up with the following, it does not give me errors but simply stops code execution during a C# fill. I had it working for finding the Item_No on Table3 and returning what it finds, I have ONLY changed this line of code since so I KNOW this is the issue.
Here is what I could come up with that is not working:
SELECT Table1.ID,
Table2.Order_Qty As [Qty of Full Order], Table2.Item_No As [Set No]
FROM Table2
LEFT JOIN Table3
ON Table2.Item_No = Table3.Item_No
AND Table2.Order_No = Table3.Order_No
LEFT JOIN Table1
ON Table1.Order_No = Table2.Order_No
AND Table1.ID = Table3.ID
WHERE Table2.Item_No = #m_strUserEnteredSeachValue
ORDER BY Table2.Order_No DESC
*Example Data: *
Table 1
+----------+--------------+-------------------+
| Order_No | Sub_Order_No | Sub_Order_Contact |
+==========+==============+===================+
| 1 | 1 | John Doe |
+----------+--------------+-------------------+
| 1 | 2 | Jane Doe |
+----------+--------------+-------------------+
| 1 | 3 | Foo |
+----------+--------------+-------------------+
| 1 | 4 | Bar |
+----------+--------------+-------------------+
| 1 | 5 | Foo2 |
+----------+--------------+-------------------+
Table 2
+----------+--------------+-------------------+
| Order_No | Item_No | Customer_Item_Name|
+==========+==============+===================+
| 1 | 1 | 1234567890 |
+----------+--------------+-------------------+
| 1 | 2 | 1234567891 |
+----------+--------------+-------------------+
| 1 | 3 | 1234567892 |
+----------+--------------+-------------------+
| 1 | 4 | 1234567893 |
+----------+--------------+-------------------+
| 1 | 5 | 1234567894 |
+----------+--------------+-------------------+
| 1 | 6 | 1234567895 |
+----------+--------------+-------------------+
| 2 | 1 | 0987654321 |
+----------+--------------+-------------------+
| 2 | 2 | 0987654322 |
+----------+--------------+-------------------+
| 2 | 3 | 0987654323 |
+----------+--------------+-------------------+
| 3 | 1 | 1234567893 |
+----------+--------------+-------------------+
And Table 3
+----------+--------------+-------------------+--------------+
| Order_No | Item_No | Customer_Item_Name| Sub_Order_No |
+==========+==============+===================+==============+
| 1 | 1 | 1234567890 | 1 |
+----------+--------------+-------------------+--------------+
| 1 | 2 | 1234567891 | 2 |
+----------+--------------+-------------------+--------------+
| 1 | 3 | 1234567892 | 2 |
+----------+--------------+-------------------+--------------+
| 1 | 4 | 1234567893 | 3 |
+----------+--------------+-------------------+--------------+
| 1 | 5 | 1234567894 | 4 |
+----------+--------------+-------------------+--------------+
| 1 | 6 | 1234567895 | 4 |
+----------+--------------+-------------------+--------------+
| 1 | 4 | 1234567893 | 4 |
+----------+--------------+-------------------+--------------+
The Result I am looking for: If I search for Item 1234567893
+----------+--------------+-------------------+--------------+-------------------+
| Order_No | Item_No | Customer_Item_Name| Sub_Order_No | Sub_Order_Contact |
+==========+==============+===================+==============+===================+
| 3 | 1 | 1234567893 | | |
+----------+--------------+-------------------+--------------+-------------------+
| 1 | 4 | 1234567893 | 3 | Foo |
+----------+--------------+-------------------+--------------+-------------------+
| 1 | 4 | 1234567893 | 4 | Bar |
+----------+--------------+-------------------+--------------+-------------------+
A pragmatic answer to a problem like this is to split it into a couple of queries. Query Table #2 first, and then based on that result set, run additional queries into #1 or #3.
Another angle is to query on Table #2 and use subqueries to reach-out-there into Table #1 or Table #3 to fetch data you need.
Try this:
declare #m_strUserEnteredSeachValue varchar(10) = '1234567893';
with a as
(
select
Order_No, Item_No, Customer_Item_Name
from
Table2
UNION
select
Order_No, Item_No, Customer_Item_Name
from
Table3
)
select
a.Order_No,
a.Item_No,
a.Customer_Item_Name,
Table3.Sub_Order_No,
Table1.Sub_Order_Contact
from
a
left join
Table3
on
Table3.Order_No=a.Order_No
and Table3.Item_No=a.Item_No
and Table3.Customer_Item_Name=a.Customer_Item_Name
left join
Table1
on
Table1.Sub_Order_No = Table3.Sub_Order_No
where
#m_strUserEnteredSeachValue = a.Customer_Item_Name
order by
a.Item_No, Table3.Sub_Order_No
SqlFiddle demo: http://www.sqlfiddle.com/#!3/973d8/3
I have no idea if this is what you are trying to arrive at or not, since it's difficult to understand from you question. All I know that this query gives the dataset that you put in OP.