Insert a records count into a different table - sql

I need to write the count of all records in one table into another. I am using an INSET INTO statement, it seems pretty straightforward. Access returns that I am making a syntax mistake. Here is my query:
INSERT INTO tblA (Field1)
VALUES (SELECT COUNT(tblB.ID) FROM tblB);
What is the problem here? Access documentation says you are allowed to give a query as argument for VALUES. Is it the aggregation that Access doesn't like?

I would do it with insert . . . select as Tim recommends. But, I want to explain what is wrong with your syntax.
The syntax for insert . . . values is:
insert into tblA(field1)
values ( . . . );
Notice the parentheses. In addition, a subquery always needs to have its own parentheses. So, to make your version work, you need an extra set of parentheses:
INSERT INTO tblA (Field1)
VALUES ( (SELECT COUNT(tblB.ID) FROM tblB) );

Use INSERT INTO...SELECT:
INSERT INTO tblA (Field1)
SELECT COUNT(tblB.ID) FROM tblB

this the easy way we can use COALESCE, i hope it's usefull
SELECT
table1.id,
COALESCE(table2_count, 0) AS table2_count,
COALESCE(table3_count, 0) AS table3_count
FROM users
LEFT JOIN (
SELECT id, COUNT(*) AS table2_count
FROM table2
GROUP BY id
) table2_counts ON table2_counts.id = table1.id
LEFT JOIN (
SELECT id, COUNT(*) AS table3_count
FROM table3
GROUP BY id
) table3_counts ON table3_counts.id = table1.id

Related

Pass values as parameter from select query

I want to pass values from output of select query to another query. Basically both queries will be part of a stored procedure. e.g.
select Id, RelId
from tables
There will be multiple rows returned by above query and I want to pass them to the following query
select name
from table2
where Id = #Id and MgId = #RelId
Please suggest
You cannot pass multiple values in SQL.
But maybe you can just join your 2 tables, that would be far more efficient.
Not knowing your table schemes I suggest something like this. You might have to adapt this to your actual table schemas off course
select name
from table2 t2
inner join tables t on t2.Id = t.Id
and t2.MgId = t.RelId
EDIT
As Gordon mentioned in his answer, this approach can show double rows in your result.
If you don't want that than here are 2 ways of getting rid of the doubles
select distinct name
from ...
or by grouping by adding this at the end of the statement
group by name
Though this will work, avoiding the doubles like in Gordon's answer is better
I would suggest using exists:
select t2.name
from table2 t2
where exists (select 1
from tables t
where t2.Id = t.Id and t2.MgId = t.RelId
);
The difference between exists and join is that this will not generate duplicates, if there are multiple matches between the tables.
Or...
SELECT *
INTO #Table1
FROM ...
SELECT *
INTO #Table2
FROM ...
SELECT *
FROM #Table1 T1
JOIN #Table2 T2
DROP TABLE #Table1, #Table2

SQL select from column where column equals table variable?

I'm a serious SQL noob so any help is appreciated. I'm having a hard time even explaining what I'm trying to do so I'll lay out what I have so far:
DECLARE #UserIDInt table (ID int);
INSERT into #UserIDInt
SELECT UserId
FROM [LcsCDR].[dbo].[Users]
WHERE [LcsCDR].[dbo].[Users].[UserUri] LIKE '%example';
SELECT *
FROM [LcsCDR].[dbo].[SessionDetails]
WHERE [LcsCDR].[dbo].[SessionDetails].[User1Id] = #UserIDInt;
"DECLARE #UserIDInt table (ID int);"
This creates my variable with a column called "ID"
INSERT into #UserIDInt
SELECT UserId
FROM [LcsCDR].[dbo].[Users]
WHERE [LcsCDR].[dbo].[Users].[UserUri] LIKE '%example';
This adds numeric values into the ID column based on whether or not the WHERE statement matched
SELECT *
FROM [LcsCDR].[dbo].[SessionDetails]
WHERE [LcsCDR].[dbo].[SessionDetails].[User1Id] = #UserIDInt;
This is where I am lost. I am trying to return all rows from [LcsCDR].[dbo].[SessionDetails] if the column [LcsCDR].[dbo].[SessionDetails].[User1Id] matches anything in my variable. The problem (I think) I'm having is that SQL can't look within the variable's column to find multiple values. Basically, the ID column in my variable #UserIDInt will contain a bunch of numeric values.
How do I perform the final SELECT statement and have SQL return all results if [LcsCDR].[dbo].[SessionDetails].[User1Id] matches anything within my #UserIDInt.ID column?
I am using SQL Server 2014.
Apologies if I explained it badly. Not sure how else to ask the question :)
using inner join:
select sd.*
from [lcscdr].[dbo].[sessiondetails] sd
inner join #useridint i
on i.id = sd.user1id;
or using exists():
select sd.*
from [lcscdr].[dbo].[sessiondetails] sd
where exists (
select 1
from #useridint i
where i.id = sd.user1id
);
or using in():
select sd.*
from [lcscdr].[dbo].[sessiondetails] sd
where sd.user1id in (
select id
from #useridint i
);
rextester demo: http://rextester.com/UVCB28056
Use EXISTS:
SELECT T1.*
FROM [lcscdr].[dbo].[sessiondetails] T1 WHERE EXISTS (
SELECT 1
FROM #useridint T2
WHERE T2.id = T1.user1id
);

How to Get matching records using Exists statement along with a condition on the main table

I have a problem regarding sql 'exists' statement and I will highly appreciate any kind of help.
Let me explain you what I need to accomplish.
I have two tables where I would like to get matching records from table1 which also exits in table2. Till this, it is simple. However, I also want to get those records from table1 along with matching records which has a particular column NULL in Table1. In other words I need to get those records from Table1 either they exist in Table2 or they have a specific column NULL. I wrote the following query to accomplish this.
CREATE TABLE #Table1(ID INT, Column2 INT NULL)
CREATE TABLE #Table2(ID INT)
INSERT INTO #Table1 VALUES(1, NULL)
INSERT INTO #Table2 VALUES(2)
select * from #Table1
WHERE EXISTS (SELECT NULL from #Table2 where #Table2.ID = #Table1.ID OR #Table1.Column2 IS NULL)
DROP TABLE #Table1;
DROP TABLE #Table2;
This query works when Table2 is not empty. However, if Table2 is empty then IS NULL condition does not work.
In order to resolve this I also tried adding a dummy record in case Table2 is empty by adding a union, but it does not resolve my problem either because there will always a record when I should get 0 records.
Like this
select * from #Table1
WHERE EXISTS (SELECT ID WHERE NOT EXISTS (SELECT * FROM #Table2)
UNION
SELECT NULL from #Table2 where #Table2.ID = #Table1.ID OR #Table1.Column2 IS NULL)
Note: I know this can be solved using joins but I would like to solve it using Exists statement because this is the part of a large system which simply cannot be converted to joins. I have given the above as a simple scenario.
Any kind of help would be highly appreciated.
Will this work?
WHERE EXISTS (SELECT 1 from #Table2 where #Table2.ID = #Table1.ID) OR #Table1.Column2 IS NULL
Move the condition outside the EXISTS. It is closer to how you describe the problem anyway:
select t1.*
from #Table1 t1.
WHERE t1.Column2 IS NULL OR
EXISTS (SELECT 1 from #Table2 t2 where t2.ID = t1.ID);
Notes:
Although EXISTS (SELECT NULL . . . ) is allowed an works, I find it highly misleading. In practice, NULL often represents missing values so the result is a bit of cognitive dissonance. Besides, SELECT 1 is easier to type.
I recommend table aliases; they make the query easier to write and to read.

Select Into error

SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
INTO #tempTable
FROM xfqti_virtuemart_products_pt_pt
Gives syntax error, I'm about to pull my hair off
Being Virtuemart, I'm guessing this is a MySQL database. If so, the correct syntax for creating a temp table is:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
SELECT field1, field2
FROM yourtable;
)
That being said, your SELECT statement has two fields from two different tables, but only one of those tables is mentioned in the FROM clause of your statement. They should really both be in there and JOINed. Something like:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTableName AS
(
SELECT
t1.virtuemart_product_id,
t2.virtuemart_media_id
FROM
xfqti_virtuemart_products_pt_pt as t1
INNER JOIN xfqti_virtuemart_product_medias as t2 ON
t1.product_id = t2.product_id
)
Or something.. I can't see your tables and it's been years since I used Virtuemart, so it's just a guess at the table relationship.
Insert Into and Selecthave these sintax
Insert into your_Table (col1,col2)
SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
FROM xfqti_virtuemart_products_pt_pt
for create table
Create your_Table as
SELECT
xfqti_virtuemart_products_pt_pt.virtuemart_product_id,
xfqti_virtuemart_product_medias.virtuemart_media_id
FROM xfqti_virtuemart_products_pt_pt

SQL I want to duplicate record on insert

Without using a while or forloop, is there a way to insert a record two or more times on a single insert?
Thanks
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE FROM TABLE1 )) * 2
You would need to CROSS JOIN onto a table with 2 rows. The following would work in SQL Server.
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE
FROM TABLE1, (SELECT 1 UNION ALL SELECT 2) T(C)
If you have an auxilliary numbers table you could also do
SELECT VALUE,VALUE
FROM TABLE1 JOIN Numbers ON N <=2
--first create a dummy table with 2 records
INSERT INTO TABLE2 ((VALUE,VALUE)
SELECT VALUE,VALUE FROM TABLE1, dummytable ))
This is not an elegant way, but could work easily.
If you have a table with an high enough number of records you can do the cross join with a TOP clause
INSERT INTO TABLE2
SELECT VALUE,VALUE FROM TABLE1
cross join (select top 2 TABLE_DUMMY) as DUMMY
This works for MQ SqlServer, to let it work in other DBMS you should change the TOP with the keyword needed by your DBMS