query with calculated fields - sql

I've got table
Manga
idmanga title idauthor idgenre idmagazine
and table
Author
idauthor name surname
How to get table with fields
fullname title sumofids
name+surname idmanga+idauthor+idgenre+idmagazine
I can get fullname like this
select name+' '+surname as Fullname from Author
But how to get other fields in one query?

select CONVERT(VARCHAR,idmanga)
+CONVERT(VARCHAR,idauthor)
+CONVERT(VARCHAR,idgenre)
+CONVERT(VARCHAR,idmagazine)
That should do it all in one string.
Add + ' ' + to put in spaces.
To add all the values together, your query should work to get the values for every row. If you want to group by the Name to roll the results up, use the SUM() and you'll get one row per unique name combination
create table Test ( Name varchar(10)
,idmanga int
,idauthor int
,idgenre int
,idmagazine int)
insert into Test
select 'Roger',1,2,3,4
union select 'Bob',4,5,6,7
union select 'Roger',8,9,10,11
union select 'Bob',12,13,14,15
union select 'Bill',16,17,18,19
select Name
, idmanga+idauthor+idgenre+idmagazine
from Test
select Name
, SUM(idmanga+idauthor+idgenre+idmagazine)
from Test
group by Name

Related

How to UNION all two tables into a temp table?

I've been trying to combine two tables into a temp table. My goal is to have the data of both tables available in one temp table
I tried a couple of things:
1.
SELECT * INTO #temp FROM Customers.Emails
UNION ALL
SELECT * INTO #temp FROM Customers.Location
SELECT *
INTO #temp
(Select
All column names here etc
FROM Customer.Emails
UNION
SELECT
All column names here etc
FROM Customer.Location)
When I tried 2 I got this error
Msg 263, Level 16, State 1, Line 1
Must specify table to select from.
Msg 1038, Level 15, State 5, Line 1
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Here are 3 methods to do the INSERT INTO #temp. Method 1 requires both tables to have the exact same column names and count. The other 2 methods require you to define the columns you want inserted since we aren't using SELECT * anymore.
CREATE TABLE emails (
email_address nvarchar(50)
);
CREATE TABLE locations (
email_address nvarchar(50)
);
INSERT INTO emails VALUES ('test#test.com');
INSERT INTO locations VALUES ('test2#test2.com');
--Method 1
SELECT * INTO #temp FROM emails
UNION ALL
SELECT * FROM locations
SELECT *
FROM #temp;
--Method 2
SELECT *
INTO #temp2
FROM (
SELECT
email_address
FROM emails
UNION ALL
SELECT
email_address
FROM locations
) as tbl
SELECT *
FROM #temp2;
--Method 3
WITH prelim AS (
SELECT
email_address
FROM emails
UNION ALL
SELECT
email_address
FROM locations
)
SELECT *
INTO #temp3
FROM prelim;
SELECT *
FROM #temp3;
Method 1 Results:
email_address
test#test.com
test2#test2.com
Method 2 Results:
email_address
test#test.com
test2#test2.com
Method 3 Results:
email_address
test#test.com
test2#test2.com
fiddle

Join query in specific column table

i have table with query i can get final price , i want join query to table as new column.
my query:
SELECT ID , Name FROM dbo.AshkhasList
select dbo.Person_Mande(40,'1398/01/01','1400/12/29',DEFAULT)
line 1 query call table with id and name , line 2 get final price as id.
i want join final price query line 2 as column name Price inside name in result.
i found my problem:
SELECT ID , Name , dbo.Person_Mande(ID,'1398/01/01','1400/12/29',DEFAULT) AS Mande FROM dbo.AshkhasList

Search from comma separated values

I have user tables which contains column city_id and inside this column city ids are stored as comma separated values as following:
User
user_id user_name city_id
1 ahmar_arshad 1,2,3
2 abdul_muiz 15,2,9
3 abdul_momin 1,2,13
Now I want to search rows which contains city id = 1 from city_id column.
How it can be done?
Here is a general solution, which should work on Postgres:
SELECT *
FROM yourTable
WHERE ',' || city_id || ',' LIKE '%,1,%';
Demo
The trick here is to compare the CSV list of city IDs in the form, e.g. ,1,2,3, against ,ID,, where ID can be any individual city ID.
Note that it would be best to normalize your table and store those city IDs across separate records instead of in CSV strings. This would make querying your data easier, and would probably also increase performance.
If you convert that comma separated list to an array you can use Postgres' powerful array operators:
select *
from cities
where '1' = any (string_to_array(city_id, ','));
If you need to find rows with on of several ID's
select *
from cities
where string_to_array(city_id, ',') && array['1', '2']
The && is the "overlaps" operator for arrays. If you need to find rows that contain all of a list of IDs: you can use the contains operator:
select *
from cities
where string_to_array(city_id, ',') #> array['1', '2']
Check This.
you should use string_to_array to spilt column and then use city_id='1' conditon in where clause.
select * from (
select id,user_name,unnest(string_to_array(city_id, ',')) city_id
from RT
)a where city_id='1'
Check Demo Here.
OutPut
Try this query !
SELECT *
FROM [Table Name]
WHERE city_id LIKE '1,%,%'
OR city_id LIKE '%,1,%'
OR city_id LIKE '%,%,1';
Try this One..
--**********************************************************************************
--Creating Table structure for the reference
create table #test (user_id int,user_name varchar(100),city_id varchar(25))
insert into #test values (1,'ahmar_arshad','1,2,3')
insert into #test values (1,'abdul_muiz','15,2,9')
insert into #test values (1,'abdul_momin','1,2,13')
--select * from #test
--**********************************************************************************
-- Query
select user_id,user_name,city_id from
(
select user_id,user_name,city_id,replace(city_id,',','') as City_ID2
from #test
)A
where City_ID2 like '%1%'
-- Replace comma with star(*) and then search.
--**********************************************************************************
SELECT *
FROM user
WHERE user_id LIKE '%1%';
you can search like keyword on w3school

How do I Use Count Function for different values of the same column in MS-SQL?

For DB StudentInfo and Table Student as follows:
CREATE TABLE Student
(
ID INT PRIMARY KEY IDENTITY(1,1),
Name nvarchar(255)
)
and inserting values:
Insert Into Student Values ('Ashok')`
executing it 3 times, and
Insert Into Student Values ('Achyut')
executing it 2 times and total 5 rows of data are inserted into the table.
I want to display a result counting the result with the name having 'Ashok' & 'Achyut'.
Generally for single values count in a column I use:
SELECT Count(Name) AS NoOfStudentHavingNameAshok
FROM Student
WHERE Name = 'Ashok'
but how to display the NoOfStudentHavingNameAshok & NoOfStudentHavingNameAchyut what query should I run?
You should include name in the select and group by name.
SELECT name, Count(*)
From Student
group by name
You can put conditions inside your COUNT() function:
select count(case when Name = 'Ashok' then 'X' end) as NoOfStudentHavingNameAshok,
count(case when Name = 'Achyut' then 'X' end) as NoOfStudentHavingNameAchyut
from Student

How do I select rows in table (A) sharing the same foreign key (itemId) where multiple rows in table have the values in table B

Sorry about the title, not sure how to describe without example. I trying to implement faceting of attributes in SQL Server 2008.
I have 2 tables. itemAttributes and facetParameters
Assume the following values in itemAttributes
id, itemId, name, value
---------------------------------------
1 1 keywords example1
2 1 keywords example2
3 2 color red
4 2 keywords example1
5 2 keywords example2
6 3 keywords example2
7 3 color red
8 3 color blue
Assume the following values in facetParameters
name value
----------------------
keywords example1
color red
I need to retrieve the (optional: distinct) itemIds where a given itemId has rows that contain all the values in facetParameters.
e.g. given the rows in facetParameters the query should return itemId 2. At the moment I would be using this in a CTE however given that they do not support a number of features I can work around this if there is no solution that works inside a CTE.
I have done a fair bit of sql over the years but this one has really stumped me and the shame is I keep thinking the answer must be simple.
You could join both tables, and use a having clause to ensure that all items match:
select ia.itemid
from #itemAttributes ia
inner join #facetParameters fp
on ia.name = fp.name
and ia.value = fp.value
group by ia.itemid
having count(distinct fp.name) =
(
select count(*) from #facetParameters
)
The count in the having clause assumes that the name uniquely identifies a row in the facetParameters table. If it doesn't, add an identity column to facetParameters, and use count(distinct id_column) instead of count(distinct fp.name).
Here's code to create the data set in the question:
declare #itemAttributes table (id int, itemId int,
name varchar(max), value varchar(max))
insert into #itemAttributes
select 1,1,'keywords','example1'
union all select 2,1,'keywords','example2'
union all select 3,2,'color','red'
union all select 4,2,'keywords','example1'
union all select 5,2,'keywords','example2'
union all select 6,3,'keywords','example2'
union all select 7,3,'color','red'
union all select 8,3,'color','blue'
declare #facetParameters table (name varchar(max), value varchar(max))
insert into #facetParameters
select 'keywords','example1'
union all select 'color','red'