Insert JSON into SQL table - sql

I have the following SQL Table 1:
id
name
gender
age
country
ambition
1
Peter
Male
20
Italy
Doctor
2
Angeli
Female
30
Australia
Lawyer
I want to insert into another table like this method.
Output : SQL Table 2
id
name
details json
1
Peter
{"gender":"Male","age":"20","country":"Italy","ambition":"Doctor"}
2
Angeli
{"gender":"Female","age":"30","country":"Australia","ambition":"Lawyer"}
Any suggestions on how to insert multiple records?

For all versions, starting from SQL Server 2016, you may generate the JSON content for each row using FOR JSON PATH:
SELECT
id, name,
details = (SELECT gender, age, country, ambition FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)
INTO NewTable
FROM OldTable
Starting from SQL Server 2022, you may use JSON_OBJECT():
SELECT
id, name,
details = JSON_OBJECT('gender': gender, 'age': age, 'country': country, 'ambition': ambition)
INTO NewTable
FROM OldTable

Related

How to filter condition not existed in IN list value [duplicate]

This question already has answers here:
Postgres: how to find absent users in DB
(2 answers)
Find values not present in supplied list postgres
(3 answers)
Closed 2 years ago.
Given that I have and a table country, which has column name to store name of a country.
Table schema:
Column Name | Datatype | Description
ID | int | ID of the table
name | varchar(255) | Name of the country, i.e: UK, US, China
Now if I have a list of n string values as input data to filter:
i.e: Tokyo, Japan, US, New York, UK, London, India, China, etc
How can I write a sql query to filter all the values which doesn't exist in country table
i.e: I want to return Tokyo, NewYork, London.
You can do something like this in Postgres:
select d.name from unnest(array['Japan', 'US', 'New York', 'UK', 'London', 'India', 'China']) d(name)
left join country on country.name=d.name where country.name is null
You mention that you need to filter column name, i am not tested this yet but give it a try (MySQL):
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_db' AND TABLE_NAME = 'country' AND COLUMN_NAME NOT IN ('your_list_values')
I might misunderstanding your question, you should post your country table schema for more details.
You need to transform your input (Tokyo, Japan, US, New York, UK, London, India, China) into a table. Something like this
With CTE AS (
SELECT 'Tokyo' as name UNION ALL
SELECT 'Japan' UNION ALL
SELECT 'US' UNION ALL
SELECT 'New York' UNION ALL
SELECT 'UK' UNION ALL
SELECT 'London' UNION ALL
SELECT 'India' UNION ALL
SELECT 'China'
)
select name from CTE
LEFT JOIN country ON CTE.name=country.name
WHERE country.name is NULL

How can I insert data from two tables into one?

I have three tables , both with the same fields as in the example below:
Table:
dog
-------------
name, date
Table :
cat
-------------
name, date
Table:
animal
-------------
name, date
as I transfer the dog and cat data for animal table ? I tried the select into but could not do it with two tables.
Table value:
CAT
name date
Garfield 2015-08-03
DOG
name date
Spike 2015-08-03
Source:
insert into animal values ((select * from cat,dog))
Expected result
ANIMAL
name date
Garfield 2015-08-03
Spike 2015-08-03
Try this:
insert into animal
select name, date from dog
union all
select name, date from cat
It can be done with the execution of a query ie:Join operation.Table 1, Table 2,table 3. We have the same attribute in all these three tables.Just join the attributes with table1.fieldname JOIN table2.fieldname JOIN table3.fieldname
There is no need to do a JOIN as there is no relationship between them.
Insert Into animal (name, [date])
Select name, [date]
from dog, cat

Insert data into new table from 2 tables, error duplicate destination name - Access Sql

I have 2 queries, the result of which I'm trying to insert into a new table.
Query1: Class Name Age City
A1 Jill 21 New York
Query2: Class Name Age City
A2 Joe 25 Paris
Now, the city can change when I run the queries again, but I want to insert into the new table only record with city = "New York".
So, something like INSERT INTO FinalTable(Name, Age, City)
SELECT
QUERY1.CLASS, QUERY1.NAME, QUERY1.AGE, QUERY1.CITY,
QUERY2.CLASS, QUERY2.NAME, QUERY2.AGE, QUERY2.CITY
FROM QUERY1, QUERY2
WHERE (QUERY1.CITY="NEW YORK" OR QUERY2.CITY="NEW YORK")
Only 1 query will have city as New York on one iteration.
I get a duplicate destination name error
You can use like this
INSERT INTO FinalTable(Name, Age, City)
SELECT tab.* FROM(
SELECT
QUERY1.CLASS, QUERY1.NAME, QUERY1.AGE, QUERY1.CITY,
FROM QUERY1
WHERE QUERY1.CITY="NEW YORK"
UNION ALL
SELECT
QUERY2.CLASS, QUERY2.NAME, QUERY2.AGE, QUERY2.CITY
FROM QUERY2
WHERE QUERY2.CITY="NEW YORK"
) tab

How to add table column headings to sql select statement

I have a SQL select statement like this:
select FirstName, LastName, Age from People
This will return me something like a table:
Peter Smith 34
John Walker 46
Pat Benetar 57
What I want is to insert the column headings into the first row like:
First Name Last Name Age
=========== ========== ====
Peter Smith 34
John Walker 46
Pat Benetar 57
Can someone suggest how this could be achieved?
Could you maybe create a temporary table with the headings and append the data one to this?
Neither of the answers above will work, unless all your names come after "first" in sort order.
Select FirstName, LastName
from (
select Sorter = 1, FirstName, LastName from People
union all
select 0, 'FirstName', 'LastName') X
order by Sorter, FirstName -- or whatever ordering you need
If you want to do this to all non-varchar columns as well, the CONS are (at least):
ALL your data will become VARCHAR. If you use Visual Studio for example, you will NO LONGER be able to recognize or use date values. Or int values. Or any other for that matter.
You need to explicitly provide a format to datetime values like DOB. DOB values in Varchar in the format dd-mm-yyyy (if that is what you choose to turn them into) won't sort properly.
The SQL to achieve this, however not-recommended, is
Select FirstName, LastName, Age, DOB
from (
select Sorter = 1,
Convert(Varchar(max), FirstName) as FirstName,
Convert(Varchar(max), LastName) as LastName,
Convert(Varchar(max), Age) as Age,
Convert(Varchar(max), DOB, 126) as DOB
from People
union all
select 0, 'FirstName', 'LastName', 'Age', 'DOB') X
order by Sorter, FirstName -- or whatever ordering you need
The lightest-weight way to do this is probably to do a UNION:
SELECT 'FirstName' AS FirstName, 'LastName' AS LastName
UNION ALL
SELECT FirstName, LastName
FROM People
No need to create temporary tables.
The UNION All is the solution except it should be pointed out that:
To add a header to a non-char column will require converting the column in the first part of the query.
If the converted column is used as part of the sort order then the field reference will have to be to the name of the column in the query, not the table
example:
Select Convert(varchar(25), b.integerfiled) AS [Converted Field]...
... Order by [Converted Field]

SQL - How to display the students with the same age?

the code I wrote only tells me how many students have the same age. I want their names too...
SELECT YEAR(CURRENT DATE-DATEOFBIRTH) AS AGE, COUNT(*) AS HOWMANY
FROM STUDENTS
GROUP BY YEAR(CURRENT DATE-DATEOFBIRTH);
this returns something like this:
AGE HOWMANY
--- -------
21 3
30 5
Thank you.
TABLE STUDENTS COLUMNS:
StudentID (primary key), Name(varchar), Firstname(varchar), Dateofbirth(varchar)
I was thinking of maybe using the code above and somewhere add the function concat that will put the stundents' names on the same row as in
your existing SQL looks like it has errors, but you could use GROUP_CONCAT:
add GROUP_CONTACT(colname) as another column to fetch, then split by , in your application
The resulting data set does not appear useful on the surface based on the question unless you are looking for a listing of students, their age, and how many other students are of the same age:
SELECT NAME, AGE, HOWMANY
FROM STUDENTS AS S,
(SELECT YEAR(CURRENT DATE-DATEOFBIRTH) AS AGE,
COUNT(*) AS HOWMANY
FROM STUDENTS
GROUP BY YEAR(CURRENT DATE-DATEOFBIRTH)
) AS A
WHERE YEAR(CURRENT DATE-S.DATEOFBIRTH) = A.AGE
Basically perform a self-join with the age counts you have calculated.
What about...
SELECT name FROM students WHERE age = ENTER_AGE_HERE;
You have the names and the number of students can be found by finding the number of entries you get from the query.
For example, in PHP, you can find the length of the array.
Of course, you have to change to names in my example to the names used in your database.
CREATE TABLE #Student
(
id int identity(1,1),
age int,
name varchar(255)
)
INSERT INTO #Student S
VALUES(21,'bob'),
(21,'tom'),
(21,'dick'),
(21,'william'),
(35,'mark'),
(35,'anthony')
SELECT age,COUNT(*),STUFF(
(
SELECT ',' + name
FROM #Student SS
WHERE SS.age = S.age
FOR XML PATH('')
), 1, 1, '')
FROM #Student s
GROUP BY age