SQL Server- Inserting into multople selects? - sql-server

I have about 100 select statements that look like this:
select * from users where clientid='GUID'
select * from providers where clientid='GUID'
They are really simple, but how I can I define the GUID once instead of having to put it into each select statement?

DECLARE #GuidVar VARCHAR(38);
SELECT #GuidVar ='GUID'
select * from users where clientid=#GuidVar
select * from providers where clientid=#GuidVar

use the IN clause and just put a list of comma separated IDs
SELECT * FROM users WHERE clientid IN (guid1,guid2,guid3)
MySQL IN Clause

Not sure if this might help you:
select * from users u
inner join providers p
on p.clientid = u.clientid
where u.clientid = 'GUID'
And you can continue to add inner joins for all tables and join on clientid. You will only require one where clause at the end.
The downside is that you will get all the columns in on row for each table. What you can do is to select specify tables or columns e.g select u.*, p.clientid

Related

Return multiple rows with subquery in SQL select clause

Is there a way to return multiple rows in a SQL select clause, when your subquery does not have a join/key field? My query currently looks like this. I'm wanting to return list of users and a list of contracts when there is no key between the users and contracts.
There is a handful of users, but a whole lot of contracts and I'm wanting to generate a list of each contractID next to each userID.
select
userid,
(select contractid from contracts) as contractid
from users
New here, but the suggestion for a cross join did what I wanted. thanks!
You can generate all possible combinations of users with constracts by performing a CROSS JOIN. For example:
select
u.*,
c.*
from users u
cross join contracts c
You can, then, filter the result by appending WHERE <condition> as needed.

WHERE IN as Subquery in Postgres

I have two table.
Table users has one column category_ids as array of integer integer[] which is storing as {1001,1002}
I am trying to get all categories details but it is not working.
SELECT *
FROM categories
WHERE id IN (Select category_ids from users where id=1)
When I run Select category_ids from users where id=1 I am getting result as {1001,1002}. How to make {1001,1002} as (1001,1002) or what should I change to make work above query?
You could use =ANY():
SELECT *
FROM categories
JOIN users ON categories.id =any(category_ids)
WHERE users.id = 1;
But why are you using an array?
I would use an EXISTS condition:
SELECT *
FROM categories c
WHERE EXISTS (Select *
from users u
where c.id = any(u.category_ids)
and u.id = 1);
This should possibly be the fastest option, but you should EXPLAIN ANALYZE all the answers to make sure.
SELECT *
FROM categories c
WHERE id IN (SELECT unnest(category_ids) from users where id=1)
SELECT *
FROM categories c
JOIN (SELECT unnest(category_ids) AS id from users where id=1) AS foo
ON c.id=foo.id
The first query will remove duplicates in the array due to IN(), the second will not.
I didn't test the syntax so there could be typos. Basically unnest() is a function that expands an array to a set of rows, ie it turns an array into a table that you can then use to join to other tables, or put into an IN() clause, etc. The opposite is array_agg() which is an aggregate function that returns an array of aggregated elements. These two are quite convenient.
If the optimizer turns the =ANY() query into a seq scan with a filter, then unnest() should be much faster as it should unnest the array and use nested loop index scan on categories.
You could also try this:
SELECT *
FROM categories c
WHERE id =ANY(SELECT category_ids from users where id=1)

Need query to determine number of attachments for each issue

I have a database in SQL Server that has three tables: Issues, Attachments, and Requestors. I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables. Listed below is the query that I've created, but it's not working as expected:
SELECT A.*,
B.*,
SubQuery.attachmentcount
FROM [DB].[dbo].[issues] AS A
FULL OUTER JOIN [DB].[dbo].[requestors] AS B
ON A.issue_id = B.issue_id,
(SELECT Count(attachments.attachment_id) AS AttachmentCount
FROM issues
LEFT OUTER JOIN attachments
ON issues.issue_id = attachments.issue_id
WHERE attachments.attachment_status = 1
GROUP BY issues.issue_id) AS SubQuery;
Pictures describing the three tables are listed below:
Any ideas on how to fix my query?
Thanks,
"I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables".
Based on this sentence try this:
SELECT A.Issue_ID, I.Issue_Name,r.Name, COUNT(A.attachment_id) AS Count
FROM Attachments as A
INNER JOIN Issues I on I.issue_id = A.issue_id
INNER JOIN requestors as R on A.issue_id = R.requestor_id
WHERE A.attachment_status = 1
GROUP BY A.Issue_ID, I.Issue_Name, r.Name
--Specify all columns by name (don't use *)
Keep It Simple and Try This!
SELECT i.Issue_ID, i.Issue_Name, COUNT(a.attachment_id) AS AttachmentCount
FROM attachments a JOIN
issues i ON
i.issue_id = a.issue_id
WHERE a.attachment_status = 1
GROUP BY i.Issue_ID, i.Issue_Name
Add your Desired Columns in Both Select List and Group By Clause and you are done.

SQL queries combined into one row

I'm having some difficulty combining the following queries, so that the results display in one row rather than in multiple rows:
SELECT value FROM dbo.parameter WHERE name='xxxxx.name'
SELECT dbo.contest.name AS Event_Name
FROM contest
INNER JOIN open_box on open_box.contest_id = contest.id
GROUP BY dbo.contest.name
SELECT COUNT(*) FROM open_option AS total_people
SELECT SUM(scanned) AS TotalScanned,SUM(number) AS Totalnumber
FROM dbo.open_box
GROUP BY contest_id
SELECT COUNT(*) FROM open AS reff
WHERE refer = 'True'
I would like to display data from the fields in each column similar to what is shown in the image below. Any help is appreciated!
Tab's solution is fine, I just wanted to show an alternative way of doing this. The following statement uses subqueries to get the information in one row:
SELECT
[xxxx.name]=(SELECT value FROM dbo.parameter WHERE name='xxxxx.name'),
[Event Name]=(SELECT dbo.contest.name
FROM contest
INNER JOIN open_box on open_box.contest_id = contest.id
GROUP BY dbo.contest.name),
[Total People]=(SELECT COUNT(*) FROM open_option),
[Total Scanned]=(SELECT SUM(scanned)
FROM dbo.open_box
GROUP BY contest_id),
[Total Number]=(SELECT SUM(number)
FROM dbo.open_box
GROUP BY contest_id),
Ref=(SELECT COUNT(*) FROM open WHERE refer = 'True');
This requires the Total Scanned and Total Number to be queried seperately.
Update: if you then want to INSERT that into another table there are essentially two ways to do that.
Create the table directly from the SELECT statement:
SELECT
-- the fields from the first query
INTO
[database_name].[schema_name].[new_table_name]; -- creates table new_table_name
Insert into a table that already exists from the INSERT
INSERT INTO [database_name].[schema_name].[existing_table_name](
-- the fields in the existing_table_name
)
SELECT
-- the fields from the first query
Just CROSS JOIN the five queries as derived tables:
SELECT * FROM (
Query1
) AS q1
CROSS JOIN (
Query2
) AS q2
CROSS JOIN (...
Assuming that each of your individual queries only returns one row, then this CROSS JOIN should result in only one row.

SELECTing data using a Postgres Array

I have a table that contains a column user_ids which is a Postgres Array.
I need to select all messages from another table where the column user_id is one of the ids in the given array.
In Psuedo-sql:
select users.*
from users
where id IN a_postgres_array
Any ideas?
You could use the ANY operator. From your sample:
select users.*
from users
where id =ANY(a_postgres_array)
When using two tables, it could be a JOIN, something like:
SELECT users.*
FROM users INNER JOIN table_with_array ON users.id =ANY(table_with_array.a_postgres_array)
select users.*
from users
where id IN (
select unnest(a_postgres_array)
from t
where columnX = some_value
)

Resources