SQL adding columns together - sql

I have a PostgreSQL table of 7k records. each record has 3 a unique ID and 3 fields with it. childcares, shcools, hospitals. there are all integer fields. i want to add a new column and calculate the total amount of receptors (schools,childcares,hospitals) for each row. I thought this should be pretty straighforward with adding a column and doing an insert with a select but i am not getting the results i want
alter table site add total integer;
insert into site(total) select sum(schools+childcares+hospitals) as s from site;
i have also tried a group by id in the insert select statement

You are looking for Update not Insert
Update site
set total = COALESCE(schools,0)+COALESCE(childcares,0)+COALESCE(hospitals,0)
Added COALESCE to handle NULL values.
Ex :
1 + 2 + NULL = NULL so to replace NULL with 0 I have used COALESCE.
Now it will be 1 + 2 + 0(NULL) = 3

Related

Insert followed by delete query

I want to apply the delete query first on my table and then apply the insert query on the same table.
variable_page_category table has 2 columns (page_category_id, variable_id). It's a composite primary key.
My Table can be like this:
page_category_id | 1 2 3 4 5
variable_id | 1 1 1 2 2
result_variable_page_category_delete AS (
DELETE FROM common.variable_page_category
WHERE variable_id = (dynamic_variable_json->>'id')::BIGINT
RETURNING 1
),
result_variable_page_category AS (
INSERT INTO common.variable_page_category (page_category_id, variable_id)
SELECT
(page_category_id::TEXT)::BIGINT,
(dynamic_variable_json->>'id')::BIGINT
FROM jsonb_array_elements_text((dynamic_variable_json->>'page_category_id')::JSONB) AS page_category_id
RETURNING 1
)
but this didn't perform sequentially and I'm getting this error. Both queries are individually correct.
ERROR: duplicate key value violates unique constraint \"variable_page_category_pkey\"\n Detail: Key (page_category_id, variable_id)=(1, 1) already exists.
How can I combine both the query so that delete query complete before insert?
Update query is also an option but because I'm new I can't handle update query with ease that's why trying this approach first.
Why not simply concatenate both queries using ; ??
DELETE FROM common.variable_page_category
WHERE variable_id = (dynamic_variable_json->>'id')::BIGINT
;
INSERT INTO common.variable_page_category (page_category_id, variable_id)
SELECT
(page_category_id::TEXT)::BIGINT,
(dynamic_variable_json->>'id')::BIGINT
FROM jsonb_array_elements_text((dynamic_variable_json->>'page_category_id')::JSONB) AS page_category_id
You might want to add a transaction depending on your client configuration

SQL/T-SQL Substring LEFT or Right doesn't appear to resolve

I have a two table where I have some values in a column UniqueKeys such as:
Table 1
2016_2016-2 S2_001840_30_01
2017_2017-2 D4_002213_3_01
The problem is that I am trying to match these with table 2 Unique values where the values are written in a different order such as :
Table 2:
001840_2016-2_S2_30_D_179_364128_400985
002213_2017-2_D4_3_E_752_376901_422828
Table 1 is from a different source system and table 2 is from different one. What I am trying to achieve is create a new table TABLE 3 where when the unique values match between table 1 and table 2 then insert the data from certain columns of table 1 and 2 into table 3 or else ignore the rest.
The way the Unique values should be is the following:
Year and Period: 2016-2
Cycle : S2
Unit: 001840
Group: 30
Giving the end result in Table 3 as:
001840_2016-2_S2_30
002213_2017-2_D4_3
You need to split both input values by "_" and then recombine the parts in the way they lead to the same format. Then you can join the tables.
Use two functions, the first one for values from type table 1, the second for values from table 2.
Effekt:
SELECT ...
FROM table1
JOIN table2 ON splitfunction1(table1.Key1) = splitfunction2(table2.Key2);

Insert columnA values of Table 1 into another table if match occur

I have two tables.Table A has 4 columns. And table B has two columns.I want to insert value of one column of tabel A from one column of table B based on condtion if id matches.
how i can do this ? For example if [Movieid] in 1st table =[IMDBid] in second table then insert [count] of table 1=[CB] in table 2.
i want to do it once for full table.
[column] -> these are colums
i m using sql server.
Tabel 1 : Movieid,count,
Tabel 2: IMDBid, CB
Results which i want: i want to insert values of CB column in count where Movieid=IMDBid
Tabel 1 :
(Nick Id,MovieId,Rating,MovId)-> (1,4972,6.25,?)(1,24216,7.25,?)
Tabel 2 :
(Imdbid,Title,ImdbPyId,Id)-> (4972,hello,32450,1)(24216,hi,62450,2)
Insert /fill value of MovId(tabel1) using values Id(tabel2)where MovieId(tabel1)==Imdbid(tabel2)
You can do it like,
UPDATE tabl1
SET count = (SELECT CB FROM tabl2 WHERE IMDBid = Movieid)
But it is gonna blow up if you have multiple values returning from the subquery.
So make sure to use the appropriate function to get the single value from that subquery whichever meets your requirements.
If your tables have 1:1 relationship then it should be fine. But if it is 1:n then you need to use either aggragate functions or the TOP 1 clause in that subqyery.
solution is UPDATE tabl1
SET count = (SELECT CB FROM tabl2 WHERE IMDBid = Movieid)

Single SQL Query to validate input values

I have written a Stored procedure which has three argumets
#UserID1 BIGINT
#UserID2 BIGINT
#UserID3 BIGINT
What I want to achieve is to write a single SQL query against table dbo.aspnet_UsersInRoles column ID so that #UserID1, #UserID2, #UserID3 are present in ID column of dbo.aspnet_UsersInRoles.
For example, I have received three values in variables and I want to confirm they are part of Id column. i.e. ID column of table has values 1,2,3,4,5,6,7,8,9,10 and UserID1 is 2, UserID2 is 5 and UserID3 is 7. So it should give true else false.
I can implement using three different queries but I am not getting any clue to do it in a single query.
You should be able to use something like this:
SELECT CASE WHEN SUM( CASE
WHEN #UserID1 = ID THEN 1
WHEN #UserID2 = ID THEN 1
WHEN #UserID3 = ID THEN 1
ELSE 0
END ) = 3 THEN 1 ELSE 0 AS [AllThree]
FROM aspnet_UsersInRoles
(untested code)
...assuming that the ID column is unique. If all three IDs are in the table, then you should end up with a summed value of 3. This will allow you to process the table in a single pass, but you don't get the advantages of index lookups like you get in Upendra's answer.

Insert data from one table to other using select statement and avoid duplicate data

Database: Oracle
I want to insert data from table 1 to table 2 but the catch is, primary key of table 2 is the combination of first 4 letters and last 4 numbers of the primary key of table 1.
For example:
Table 1 - primary key : abcd12349887/abcd22339887/abcder019987
In this case even if the primary key of table 1 is different, but when I extract the 1st 4 and last 4 chars, the output will be same abcd9887
So, when I use select to insert data, I get error of duplicate PK in table 2.
What I want is if the data of the PK is already present then don't add that record.
Here's my complete stored procedure:
INSERT INTO CPIPRODUCTFAMILIE
(productfamilieid, rapport, mesh, mesh_uitbreiding, productlabelid)
(SELECT DISTINCT (CONCAT(SUBSTR(p.productnummer,1,4),SUBSTR(p.productnummer,8,4)))
productnummer,
ps.rapport, ps.mesh, ps.mesh_uitbreiding, ps.productlabelid
FROM productspecificatie ps, productgroep pg,
product p left join cpiproductfamilie cpf
on (CONCAT(SUBSTR(p.productnummer,1,4),SUBSTR(p.productnummer,8,4))) = cpf.productfamilieid
WHERE p.productnummer = ps.productnummer
AND p.productgroepid = pg.productgroepid
AND cpf.productfamilieid IS NULL
AND pg.productietype = 'P'
**AND p.ROWID IN (SELECT MAX(ROWID) FROM product
GROUP BY (CONCAT(SUBSTR(productnummer,1,4),SUBSTR(productnummer,8,4))))**
AND (CONCAT(SUBSTR(p.productnummer,1,2),SUBSTR(p.productnummer,8,4))) not in
(select productfamilieid from cpiproductfamilie));
The highlighted section seems to be wrong, and because of this the data is not picking up.
Please help
Try using this.
p.productnummer IN (SELECT MAX(productnummer) FROM product
GROUP BY (CONCAT(SUBSTR(productnummer,1,4),SUBSTR(productnummer,8,4))))