Postgresql update column from one table to another - postgresql

How do i update inventory_id in TABLE2 from TABLE1 inventory_id?
So far I've tried
UPDATE TABLE2
SET
inventory_id=t1.inventory_id
FROM TABLE2 t2
INNER JOIN
TABLE1 t1
ON t1.test_id = t2.test_id
WHERE t1.test_id = t2.test_id;
But this sets all the value of inventory_id in TABLE2 as 1 instead of my expected result.
TABLE1
inventory_id test_id
1 26
2 56
3 12
4 67
TABLE2
test_id inventory_id
12
26
56
67
Such that it becomes like this?
TABLE2
test_id inventory_id
12 3
26 1
56 2
67 4

The documentation on UPDATE states:
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
...
[ FROM from_item [, ...] ]
(...)
from_item
A table expression allowing columns from other tables to appear in the
WHERE condition and update expressions. This uses the same syntax as
the FROM clause of a SELECT statement; for example, an alias for
the table name can be specified. Do not repeat the target table as a
from_item unless you intend a self-join (in which case it must appear with an alias in the from_item).
(emphasis: me)
So following that you want:
UPDATE table2 t2
SET inventory_id = t1.inventory_id
FROM table1 t1
WHERE t1.test_id = t2.test_id;
db<>fiddle
You pretty much had it but seem to got confused by the syntax you may have seen for other DBMS and mixed them.

Normally the PostgreSQL UPDATE JOIN syntax should give:
UPDATE TABLE2 t2
SET
t2.inventory_id=t1.inventory_id
FROM TABLE1 t1
WHERE t1.test_id = t2.test_id;

Related

PostgreSQL select different columns based on condition [duplicate]

I have two queries :
Queries Simplified excluding Joins
Query 1 : select ProductName,NumberofProducts (in inventory) from Table1.....;
Query 2 : select ProductName, NumberofProductssold from Table2......;
I would like to know how I can get an output as :
ProductName NumberofProducts(in inventory) ProductName NumberofProductsSold
The relationships used for getting the outputs for each query are different.
I need the output this way for my SSRS report .
(I tried the union statement but it doesnt work for the output I want to see. )
Here is an example that does a union between two completely unrelated tables: the Student and the Products table. It generates an output that is 4 columns:
select
FirstName as Column1,
LastName as Column2,
email as Column3,
null as Column4
from
Student
union
select
ProductName as Column1,
QuantityPerUnit as Column2,
null as Column3,
UnitsInStock as Column4
from
Products
Obviously you'll tweak this for your own environment...
I think you are after something like this; (Using row_number() with CTE and performing a FULL OUTER JOIN )
Fiddle example
;with t1 as (
select col1,col2, row_number() over (order by col1) rn
from table1
),
t2 as (
select col3,col4, row_number() over (order by col3) rn
from table2
)
select col1,col2,col3,col4
from t1 full outer join t2 on t1.rn = t2.rn
Tables and data :
create table table1 (col1 int, col2 int)
create table table2 (col3 int, col4 int)
insert into table1 values
(1,2),(3,4)
insert into table2 values
(10,11),(30,40),(50,60)
Results :
| COL1 | COL2 | COL3 | COL4 |
---------------------------------
| 1 | 2 | 10 | 11 |
| 3 | 4 | 30 | 40 |
| (null) | (null) | 50 | 60 |
How about,
select
col1,
col2,
null col3,
null col4
from Table1
union all
select
null col1,
null col2,
col4 col3,
col5 col4
from Table2;
The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2
If you had, for example, the following data:
col1 col2
a 1
b 2
col3 col4
y 98
z 99
You would end up with the following:
col1 col2 col3 col4
a 1 y 98
a 1 z 99
b 2 y 98
b 2 z 99
Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField
That would pull things together for you into however the data is related, giving you your result.
If you mean that both ProductName fields are to have the same value, then:
SELECT a.ProductName,a.NumberofProducts,b.ProductName,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Or, if you want the ProductName column to be displayed only once,
SELECT a.ProductName,a.NumberofProducts,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Otherwise,if any row of Table1 can be associated with any row from Table2 (even though I really wonder why anyone'd want to do that), you could give this a look.
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:
select
(select count(*) c from v$session where program = 'w3wp.exe') w3wp,
(select count(*) c from v$session) total,
sysdate
from dual;
which gives the following one-row output:
W3WP TOTAL SYSDATE
----- ----- -------------------
14 290 2020/02/18 10:45:07
(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)
Load each query into a datatable:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=143
load both datatables into the dataset:
http://msdn.microsoft.com/en-us/library/aeskbwf7%28v=vs.80%29.aspx
This is what you can do. Assuming that your ProductName column have common values.
SELECT
Table1.ProductName,
Table1.NumberofProducts,
Table2.ProductName,
Table2.NumberofProductssold
FROM Table1
INNER JOIN Table2
ON Table1.ProductName= Table2.ProductName
Try this:
SELECT ProductName,NumberofProducts ,NumberofProductssold
FROM table1
JOIN table2
ON table1.ProductName = table2.ProductName
Try this:
GET THE RECORD FOR CURRENT_MONTH, LAST_MONTH AND ALL_TIME AND MERGE THEM INTO SINGLE ARRAY
$analyticsData = $this->user->getMemberInfoCurrentMonth($userId);
$analyticsData1 = $this->user->getMemberInfoLastMonth($userId);
$analyticsData2 = $this->user->getMemberInfAllTime($userId);
foreach ($analyticsData2 as $arr) {
foreach ($analyticsData1 as $arr1) {
if ($arr->fullname == $arr1->fullname) {
$arr->last_send_count = $arr1->last_send_count;
break;
}else{
$arr->last_send_count = 0;
}
}
foreach ($analyticsData as $arr2) {
if ($arr->fullname == $arr2->fullname) {
$arr->current_send_count = $arr2->current_send_count;
break;
}else{
$arr->current_send_count = 0;
}
}
}
echo "<pre>";
print_r($analyticsData2);die;

Hoe to split data of one column in multiple columns on the basis of a condition

I have one table having data
Category. New data
Cost of equipment. 23
Price of equipments. 45
Cost of M&C. 13
Price of M&C. 12
And one another table having
Category
Equipments
M&C
Now i want data as below
Category Cost Price
Equipment 23 45
M&C 13 12
Can you please help me in solving this
You may try this. A better approach is to change your table design.
Note that while joining I had to use RTRIM to remove s from equipments. I am not aware of any other variations in your data which might not match between the two tables. Please change the join conditions appropriately ( or use a REGEXP match instead of ILIKE if they don't )
SQL Fiddle
PostgreSQL 9.6 Schema Setup:
CREATE TABLE Table1
(Category varchar(19), New_data int)
;
INSERT INTO Table1
(Category, New_data)
VALUES
('Cost of equipment', 23),
('Price of equipments', 45),
('Cost of M&C', 13),
('Price of M&C', 12)
;
CREATE TABLE Table2
(Category varchar(10))
;
INSERT INTO Table2
(Category)
VALUES
('Equipments'),
('M&C')
;
Query 1:
WITH t1
AS (
SELECT b.category
,a.new_data
FROM TABLE1 a
INNER JOIN TABLE2 b ON a.Category ILIKE '%cost%' || RTRIM(b.Category, 's') || '%'
)
,t2
AS (
SELECT c.category
,a.new_data
FROM TABLE1 a
INNER JOIN TABLE2 c ON a.Category ILIKE '%price%' || RTRIM(c.Category, 's') || '%'
)
SELECT t1.category
,t1.new_data AS cost
,t2.new_data AS price
FROM t1
INNER JOIN t2 ON t1.category = t2.category
Results:
| category | cost | price |
|------------|------|-------|
| Equipments | 23 | 45 |
| M&C | 13 | 12 |

How to find records in first table that are not present in second table

I have large table table_A that has all the records from a smaller table table_B. I want to join these tables to find only those records from table_A that do not match with table_B
Example:
Table_A has
1
2
3
4
5
Table_B has
2
3
4
I need the result to show:
result:
1
5
There are different possibilities, but I would use the NOT EXISTS. For e.g.:
Select *
FROM Table_A AS ta
WHERE NOT EXISTS (
SELECT 1
FROM Table_B AS tb
WHERE tb.Id = ta.Id
)
Hope this helps!
You can use the ff. method in order to achieve this.
SELECT
A.Value
FROM Table_A as A
LEFT JOIN Table_B as B
ON A.Value = B.Value
WHERE B.Value IS NULL

Whats wrong in this SQLite select statement?

I have two table:
Table1 is:
ID fname lname
---------------------
11 p1 p2
22 a1 a2
Table2 is:
ID fk_id field1 field2
------------------------------
1 11 2 3
2 22 5 4
and I have this statement in sqlite:
select * from Table1
where Table1.id=(select fk_id
from Table2
where (select sum([field1]-[field2])
from Table2 GROUP BY [fk_id]) > 0)
I expect that this query return all rows of Table1 but it return just one row!
why?!
I can't understand this!
It would help if there was the result.
So I guess because for table 11
sum(2 - 3) = -1
which fails for
select fk_id
from Table2
where (select sum([field1]-[field2])
from Table2 GROUP BY [fk_id]) > 0
So you only got 22 as your result.
You probably need a abs(sum([field1]-[field2]) then.

T-SQL: Selecting column from an alternate table when null

I have the following table, TableA, with data:
ID ColA
0 10
1 null
2 20
I have another table, TableB, with the following data.
ID ColB ColC
1 30 80
1 40 70
3 50 100
I need to select rows in TableA but when ColA in the row is null, I want to retrieve the value of ColB in TableB (if one exists) and use it in place of ColA. If no value in ColB exists, then the value of ColA in the result should be null. The join is done on TableA.ID and TableB.ID. TableB can have multiple rows where the ID column repeats. TableB.ID and TableB.ColC together make a row unique. So my result should look like this if ColC is limited to the value of 70:
ID ColA
0 10
1 40
2 20
Not sure how to do this. Thanks for your help!
select a.ID, COALESCE(a.ColA, b.ColB) as 'ColA'
from TableA a
left join TableB b on a.ID = b.ID and b.ColC = 70
This seems to do what you want if I have correctly interpreted your question:
SELECT a.ID,
ISNULL(a.ColA, b.ColB) ColA
FROM TableA a
LEFT JOIN
TableB b
ON a.ID = b.ID
AND b.ColC = 70
I have literally "limited to the value of 70" in ColC as you stated.
sounds like you're looking for a case statement. try case when TableA.Value is null then TableB.Value end
SQL Case Statements