insert one column data from a table into other table, but the other column data will be specified dynamically - sql

i have 2 tables.
TABLE A COLUMNS - aid , aname
TABLE B COLUMNS - bid , bname
from table A, i will pick up data from column 'aid',
AND insert it in 'bid' column of table B , but in bname column of table B, i will insert a new value. how do i do this?
create table A(aid int,aname char)
insert into A values(111, 'e')
create table B(bid int, bname char)
insert into B (bid,bname)
bid will take value from the query : select aid from a
bname will get a new value -m
expected result should be : THE TABLE B WILL HAVE :
bid bname
--- -----
111 m

Try this:
insert into b (bid, bname) select aid, 'm' as bname_fixed_val from a
Two facts enabled the solution above:
The insert .. select clause allows you to insert the values returned with any select.
You can return constant values as fields with select, like for instance:
SELECT 0 as id, 'John' as name
Combining these two points together, I used an insert..select clause to select the field value from the first table (aid), along with a constant value for the second field (m). The AS bname_fixed_val clause is simply a field alias, and can be omitted.
For more information on SQL, here 's a link: http://www8.silversand.net/techdoc/teachsql/index.htm, although googling it wouldn't hurt also.

Related

Insert only new records that are added to TABLE A into TABLE B

Presently I have 2 tables in a SQL database: Table A and Table B
I am using the syntax
Insert Into TABLE B
Select id, col, col, col......
From TABLE A
Where id NOT IN (SELECT id from TABLE B)
End;
This syntax works great. However, if I delete a record that is in TABLE B, the above code would in return, insert the deleted record back into TABLE B. I do not want this to happen. Is there another way to insert a record that is NOT IN TABLE B "only once". It should basically ignore all other previously inserted records which were inserted into TABLE B. If it was deleted it should not be inserted a second time.
I want it to only insert only new records added to TABLE A.
If the ID is consecutive integer then you can use:
Insert Into TABLE B
Select id, col, col, col......
From TABLE A
where ID > select(max(id) from table B)

Using another table as value type

I have been searching this and can not find the proper answer if I need an JOIN or SUBQUERY, I have tried multiple ways if doing this and honestly I am hitting a major wall. I am trying to do something simple and I don't know how to progress
I have two tables I am trying to use: table 1) data 2) mapping
table 1 is like this the headers are :
Date
Value1
Value2
Value3
Value4
Etc.
Value in CSV style for example would be:
1/1/10,1,2,3,4
1/2/10,5,6,7,8
1/3/10,9,10,11,12
table 2 has only one row though, here are the headers and one row
Value1
Value2
Value3
Value4
The one row would be like:
Description1, Description2, Description3, Description4
So, I want to be able to, for example do a SELECT FROM table 1 and join in the Description for each matching row where the Column names are the same, so sample output based on the above would be to be like this:
1/1/10,1,Description1,2,Description2,3,Description3,4,Description4
1/2/10,5,Description1,6,Description2,7,Description3,8,Description4
Etc
Since there's just one row in table2 and no key, you can simply join it.
select *
from table1
join table2
Since there's just one row in table2 it's questionable why it exists at all. This could be done without a join at all.
select date, value1, 'Description1', value2, 'Description2', value3, 'Description3', value4, 'Description4'
from table1;
There's likely a better way to do this. Having columns like value1, value2, and value3 usually indicates poor table design. Instead of having four value columns, you should have four value rows. And instead of having a table with four columns of descriptions, it should be four rows of descriptions.
For example, let's say you're storing items in an order. An order can have many items. Rather than having a column for each item in an order like item1, item2, item3, you'd have a row for each item in a join table. Below that's order_items. Descriptions of the items is stored separately in its own table, one row per item.
user
----
id bigint primary key
name text not null
items
-----
id bigint primary key
name text not null
orders
------
id bigint primary key
user_id bigint references users(id)
created_at datetime
order_items
-----------
order_id bigint references orders(id)
item_id bigint references items(id)
If you want to look up all the items in an order, with their names, you'd use the order_items table to get all the items in an order, and join with the items table to get each item's name.
select i.name
from order_items oi
join items i on i.id = oi.item_id
where oi.order_id = ?
Comma separated lists of values are awkward to handle.
Rather than a CSV, storing the values in a mapping table is typically used.
If I understand correctly then I believe that the following may demonstrate along the lines of what you want:-
DROP TABLE IF EXISTS table1 /* Assigned Values per date (the mapping table)*/;
DROP TABLE If EXISTS table2 /* Values */;
CREATE TABLE IF NOT EXISTS table2 (valueid INTEGER PRIMARY KEY,value_description TEXT);
CREATE TABLE IF NOT EXISTS table1 (date TEXT, valueid_reference INTEGER REFERENCES table2(valueid),value INTEGER, UNIQUE(date, valueid_reference));
INSERT INTO table2 VALUES (1,'Value1 Description'),(2,'Value2 Description'),(3,'Value3 Description'),(4,'Value4 Description');
INSERT INTO table1 VALUES
('1/1/10',1,1),('1/1/10',2,2),('1/1/10',3,3),('1/1/10',4,4),
('1/2/10',1,5),('1/2/10',2,6),('1/2/10',3,7),('1/2/10',4,8)
;
SELECT date||','||group_concat(value||','||value_description) AS all_values_and_descriptions FROM table1 JOIN table2 ON valueid_reference = valueid GROUP BY date;
SELECT * FROM table1;
This results in :-
Noting that the REFRENCES (Foreign Key) will be a noop unless Foreign Key support is enabled. However, without it will still work.
As can be seen each value per date is an individual row in table 1 (so 4 rows per date). It is the group_concat function that is used to get all the values per date in conjunction with the GROUP BY clause which creates a set of rows (a Group) for each date.
The 2nd SELECT shows the rows in table1 :-

Create table with other table data

Following query works but i want with 2 fields
CREATE TABLE TOTAPPS (ANUM) AS SELECT a.A# FROM APPLICANT a.
This is work that
//TOTAPPS
ANUM
--------
if i want to create with 2 fields?
//Totapps
ANUM NUMBER
---------------------------
how should i create the table? in order to get the correct out?
and the NUMBER is refer to the ANUM , for example
CREATE TABLE TOTAPPS (ANUM) AS SELECT a.A# FROM APPLICANT a,
(NUMBER) AS SELECT COUNT(*) FROM a.A#;
but it's failed to work.
Calling a column NUMBER is not correct as it is a reserved word. Assuming from your second query that you want to add to your table distinct values of a.A# and the count of these values in the table, you should try this:
CREATE TABLE TOTAPPS (ANUM, MYNUMBER) AS
SELECT a.A#, COUNT(a.A#) FROM APPLICANT a GROUP BY a.A#;

Insert into table select from table a and table b where

I want to insert data into a table by joining two tables with a where condition that each id matches.
INSERT INTO SALES(T_ID, SF)
SELECT B.T_ID, B.SF
FROM HIS B, SALES C
WHERE C.REP_ID=B.REP_ID;
I am getting an error that I cannot insert NULL into ("c.REP_ID")
I am not trying to insert anything into c.rep_id. I want to insert values into t_id, sf from HIS table where the rep_id on his table = rep id on sales table.
INSERT INTO SALES (T_ID, SF)
SELECT h.T_ID, h.SF FROM HIS h, SALES C
WHERE C.REP_ID=B.REP_ID;
Note: Make sure that the data comes from select tables is equally compare and valid with the datatypes of the columns where you inserting.
The error simply means that the column REP_ID in the SALES table has a NOT NULL constraint. Your INSERT statement doesn't insert any value into that column (you only insert T_ID and SF) and presumably there are no before-row triggers that will set that column for you.

SQL unpivot & insert

Sorry for the lack of info -- SQL Server 2008.
I'm struggling to get a couple of column values from table A into a new row in table B for each row in A where a column isn't null.
Table A's structure is as:
UserID | ClientUserID | ClientSessionID | [and a load of other irrelevant columns)
Table B:
UserID | Name | Value
I want to create rows in table B for each non-null ClientUserID or ClientSessionID in A - using the column name as B's "Name", and column value as "B's Value".
I'm struggling to write my "unpivot" statement - just getting the syntax correct! I'm trying to follow along with some samples but can't
Here's my SQL query so far - any further help would be appreciated (just getting this SELECT is frustrating me, let alone doing the insert!)
SELECT UserID, ClientUserID, ClientSessionID FROM websiteuser WHERE ClientSessionID IS NOT null
This gives me the rows that I need to perform actions upon -- but I just can't get the syntax correct for UNPIVOTing this data and turning it into my insert.
You can unpivot records in this fashion by using UNION to get each new row:
INSERT INTO TableB (UserID, Name, Value)
SELECT UserID, 'ClientUserID' AS Name, ClientUserID AS Value
FROM TableA
WHERE ClientUserID IS NOT NULL
UNION ALL
SELECT UserID, 'ClientSessionID' AS Name, ClientSessionID AS Value
FROM TableA
WHERE ClientSessionID IS NOT NULL
I am using UNION ALL in this case as UNION implies a DISTINCT operation across the entire set, which should normally be unnecessary when pivoting unique records.
If your ClientUserID and ClientSessionID columns are not the same datatype, you may have to cast one or both to the same.