Sum on subqueries on SQL Server - sql

I have a query with some subqueries inside and I want to add a sum query to sum them all.
How can I do that?
example:
Id,
(SELECT COUNT(*) FROM table1 LEFT JOIN table2 on ...) as col1,
(SELECT COUNT(*) FROM table3 LEFT JOIN table4 on ...) as col2,
** Sum of both col1 and col2 here **

Try this:
SELECT ID, col1, col2, [Total] = (col1 + col2)
FROM (
SELECT Id,
(SELECT COUNT(*) FROM table1 LEFT JOIN table2 on ...) as col1,
(SELECT COUNT(*) FROM table3 LEFT JOIN table4 on ...) as col2
FROM [TABLE]) T
Hope that helps.

the easiest way would be to treat all your query as a subquery
select Id, col1 + col2 as total
from
(<yourCode>) s
Because it's not possible to use alias in the same "level of query" in the select clause.

Related

Using column names and count togetger

I am new to SQL.
I am currently trying to write a query where i would like to list down all the details in my tables. I am using joins to get the together and everything is working fine. Where i get stuck is when i try to use count with my other columns. The issue is that the count i am referring to is a text field and as per that table the same id appears multiple times and i want to get the count from my query. My query looks like this
select col1, col2, col3, count(col4)
from table1 c
left join table2 a on c.id = a.id
however this does not work. I would appreciate any leads.
Use and study on group by. Your code should be something like below.
select col1, col2, col3, count(col4)
from table1 c
left join table2 a on c.id = a.id
group by col1, col2, col3
You need to add group by clause
select col1, col2, col3, count(col4)
from table1 c
left join table2 a on c.id = a.id
group by col1, col2, col3

Standard SQL - Delete all rows in table 1 that exist in table 2

Table 1 has 101,915 rows and Table 2 has 49,466 where all of them exist in Table 1. Table 1 should have 101,915 - 49,466 = 52,449 after the query.
I tried querying a left join but it returns only 8,269 rows.
SELECT
A.*
FROM
`table1` A
LEFT JOIN
`table2` B
ON
A.interval_uid = B.interval_uid
WHERE
B.interval_uid IS NULL
I used interval_uid as key field but all the repeated rows are identical in both tables.
Try this, If the schema is same, following shall work
INSERT INTO `table3` SELECT
*
FROM
`table1` A
WHERE
A.interval_uid NOT IN (SELECT B.interval_uid FROM `table2` B)
Try using operator EXCEPT for SQL. More info needed find here
SELECT col1, col2, col3,..
FROM table1
EXCEPT
SELECT col1, col2, col3,..
FROM table2;
Insert query as follows:
Insert into table3
SELECT col1, col2, col3,..
FROM table1
EXCEPT
SELECT col1, col2, col3,..
FROM table2;
Note: Columns specified in the query must be equivalent w.r.to., table1 & table2
Please use below query for your desired result..
WITH CTE
AS (
SELECT *
FROM Table_1
EXCEPT
SELECT *
FROM Table_2
)
INSERT INTO Table_3
SELECT *
FROM CTE
Please try this one if you don't want to insert in table 3.
SELECT * FROM Table_1
EXCEPT
SELECT * FROM Table_2
you can use this following logic-
Note: Delete is a risky operation. Please try with test data first.
DELETE table1
FROM table1
INNER JOIN table2 ON Table1.interval_uid = Table2.interval_uid
This is what I wanted:
WITH
unwanted_rows AS (
SELECT
a.*
FROM
`table` a
JOIN (
SELECT
interval_uid,
COUNT(*)
FROM
`table`
GROUP BY
interval_uid
HAVING
COUNT(*) > 1) b
ON
a.interval_uid = b.interval_uid
WHERE
duration IS NULL
)
SELECT
*
FROM
`table` EXCEPT DISTINCT
SELECT
*
FROM
unwanted_rows

How to improve this inline query?

I'm a sales-force developer, I got a requirement to write a SQL query and I did it, but the performance in very low. Could you please help me here?
My query is like this:
select col1, col2,col3,col4
from table1
where col1 is not null
and col2='ABC'
and (col3 IN (SELECT field1 FROM table 2)
OR col4 in('A','B','C'))
Is there someway I can optimize this for better performance?
Update
I used left outer join to achieve it, Is that the correct way?
Try these queries:
SELECT col1, col2,col3,col4 FROM TABLE1 T1
WHERE (EXISTS (SELECT 1 FROM TABLE2 T2 WHERE T1.COL3 = T2.FIELD1)
OR COL4 IN ('A','B','C'))
SELECT col1, col2,col3,col4 FROM TABLE1 T1
WHERE EXISTS (SELECT 1 FROM TABLE2 T2 WHERE T1.COL3 = T2.FIELD1)
UNION
SELECT col1, col2,col3,col4 FROM TABLE1 T1 WHERE COL4 IN ('A','B','C')

How to create sequential ID number when using SELECT * INTO

I have a complex stored procedure that is collecting data from many tables and inserting it into MyTable. It inserts over 1.5 M records.
What would be the most efficient way to create sequential ID number when populating MyTable
The structure of the table looks like this:
IF OBJECT_ID ('MyTable', 'U') IS NOT NULL
DROP TABLE MyTable;
SELECT *
INTO MyTable
FROM
(SELECT
col1, col2, col3
FROM
Table1
INNER JOIN
Table2 ON...
INNER JOIN
Table3 ON...
INNER JOIN
Table4 ON...
WHERE
Condition1,
Condition2) T
SELECT ID = IDENTITY(INT, 1, 1),* INTO MyTable FROM (
SELECT
col1,
col2,
col3
FROM Table1 INNER JOIN Table2 ON...
Table3 INNER JOIN Table4 ON...
WHERE Condition1,
Condition2
) T
ID = IDENTITY(INT, 1, 1) will create an identity ID that auto increments, i didnt test the code
I think simple row_number() is helpfull as below:
IF OBJECT_ID ('MyTable', 'U') IS NOT NULL
DROP TABLE MyTable;
SELECT * INTO MyTable FROM (
SELECT
RowNum = Row_Number() over (order by (Select NULL)) --Instead you can generate based on any column in the table
col1,
col2,
col3
FROM Table1 INNER JOIN Table2 ON...
Table3 INNER JOIN Table4 ON...
WHERE Condition1,
Condition2
) T
As Gabri demonstrated, you can use IDENTITY with a SELECT INTO statement. This will make that column and IDENTITY column. If you don't want it to be an IDENTITY column you can use ROW_NUMBER; this will work on any SQL 2005+ system.
SELECT ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), *
INTO MyTable FROM
(
SELECT
col1,
col2,
col3
FROM Table1 INNER JOIN Table2 ON...
Table3 INNER JOIN Table4 ON...
WHERE Condition1, Condition2
) T;

In SQL can I Perform Logic on Multiple Columns, which are SELECT Statements?

I am trying to accomplish the following, and I am not sure if it is possible. I have a SELECT Statement that contains an inner SELECT for two of the table columns like so:
SELECT
col1,
col2,
(SELECT SUM(col1)
FROM table2)
AS FirstResultToAdd,
(SELECT SUM(col2)
FROM table3)
AS SecondResultToAdd,
FROM Table1
So my question is: Is it possible to perform a calculation, such as doing a SUM of "FirstResultToAdd" and "SecondResultToAdd, and returning that as a single column result on "Table1"? Also to keep in mind, I have excluded any joins of the tables to keep the example simple.
I believe you want to perform some logic on the result of Sub-query
To add the two sub-query result
SELECT col1,
col2,
(SELECT col1
FROM table2)
AS FirstResultToAdd,
(SELECT col2
FROM table3)
AS SecondResultToAdd,
(SELECT col1
FROM table2)
+
(SELECT col2
FROM table3)
AS total
FROM table1
To make the query more readable you can make the original query as Sub-Select and perform the logic in Outer query
just nest one more time...
select col1, col2, sum( FirstResultToAdd )
from (
SELECT
col1,
col2,
(SELECT col1
FROM table2)
AS FirstResultToAdd,
(SELECT col2
FROM table3)
AS SecondResultToAdd,
FROM Table1
)
Edit: Fixed Group By
Try this:
Select A.Col1,
A.Col2,
(B.Col3 + C.Col4)
From(
(Select Col1,
Col2
From [Table1]) A
Inner join (Select Sum(Col3) AS Col3
From [Table2]) B on 1 = 1
Inner join (Select Sum(Col4) AS Col4
From [Table3]) C on 1 = 1
)
Group By A.Col1,
A.Col2,
B.Col3,
C.Col4