SQL query to find rows where 1 column value matches another column on another row - sql

I have a database table with a column called 'symbol', that is unique via a non-clustered index.
We now need to change the data in the 'symbol' column, using the data from another column in the same table, say column2.
Trying to do an update, e.g.
update table
set symbol = column2
where column2 <> '' and
deleted = 0
results in a 'Cannot insert duplicate key row in object' error, so there must be 1 or more rows existing in the table that already have a value in the symbol column that is equal to the value in column2, or there are some rows that have a duplicate column 2 value.
I can find the rows that have duplicates in column2, but I'm struggling to come up with a query to find those rows that have a value in the symbol column that exists in any row in column2. Any one got any ideas?
Thanks.

select t1.symbol, count(0) as rows
from table t1
join table t2 on t2.column2 = t1.symbol
group by t1.symbol

Test data:
symbol column2
----------- -----------
1 1
2 1
3 3
4 5
find those rows that have a value in the symbol column that exists in
any row in column2.
select symbol, column2
from table
where symbol in (select column2
from table)
Result:
symbol column2
----------- -----------
1 1
3 3
Or possibly this depending on what result you want.
select symbol, column2
from table as T1
where exists (select *
from table as T2
where T1.symbol = T2.column2 and
T1.symbol <> T2.symbol)
Result:
symbol column2
----------- -----------
1 1

Related

SQL Server : select column with 3 matching characters

I am selecting the records from 2 tables in which the 1st table column named DESC (first 3 characters) should match with the project column of the 2nd table.
I want to get the last 2 characters from Table 1 column DESC to be added in my output, but the last 2 characters are not present in Table 2 column project.
select SUBSTRING(a.[DESC], 1, 3)
from Table1 a
join Table2 b on SUBSTRING(a.[DESC], 1, 3) = b.project
Input: 1st Table DESC Column: Value: '2AB F YY'
2nd Table Project Column: Value: '2AB'
Expected Output: Return all the records of value 2AB
Column result:
'2AB YY'
Wrong output: all the records of value starting other then 2AB
One option is as follows
with data
as (
select SUBSTRING(a.[DESC],1,3) as first_3_characters,
,REVERSE(SUBSTRING(REVERSE(a.[DESC]),1,2)) as last_2_char_tab1
,REVERSE(SUBSTRING(REVERSE(b.project),1,2)) as last_2_char_tab2 characters_tab2
from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project
)
select *,CONCAT(first_3_characters,last_2_characters)
from data
where last_2_char_tab1 <> last_2_char_tab2
Since you don't seem to need data from Table2, an EXISTS could be used for this.
And RIGHT can be used to get the last N characters of a string.
SELECT
CONCAT(LEFT([DESC], 3),' ', RIGHT([DESC], 2))
FROM Table1 t1
WHERE EXISTS
(
SELECT 1
FROM Table2 t2
WHERE t2.project = LEFT(t1.[DESC], 3)
)
ORDER BY 1;

SQL join of multiple queries using CTE

WITH group1 AS
(
SELECT
[column1],
[column2]
FROM
table1
),
Group2 AS
(
SELECT
(column3),
COUNT(column3)
FROM
table 2 AS Count
WHERE
(year (date_value) = 2018 and month(Date_vaLue) = 2)
GROUP BY
column2
)
SELECT *
FROM group1
JOIN group2 ON group1. table1 = group2.table2;
I get an error:
No column name was specified for column 2 of 'group2'
As this isn't a column and is just an identifier I am confused why it thinks the code (Group2 AS (Select (column3 ),) is a column.
I am new at sql so this might just be a silly error
Column 1 is a name and column two is a unique key for that name
Column 2 and column 3 contain the same exact data and I am simply trying to show the number of times it occurs in the DB on the column 3 table, including 0, and relate it back to column 1.
Each datapoint in column 3 contains only data from column2.
Thanks in advance!
There are so many errors in that query, I don't know where to start
In a cte each column must have a name. select columnname makes the resulting column named columnname. An aggregation function like count does not set a column name, so your second column in your second cte does not have a name, as the error states. Use
SELECT column, count(othercolumn) AS ctcol ...
You can't add columns you don't use in the grouping to your select list without an aggregation function. Furthermore you can't add a column aggregated and unggregated to the select list. But I suppose, that's only a typo
SELECT column2, COUNT(column3) AS ctcol
FROM tablexy
...
GROUP BY column2
Your cte don't have any columns named table1 or table2, so your join won't work. Use column named from the cte
SELECT * FROM group1 JOIN group2 ON group1.column2 = group2.column2
I think you need to name the column COUNT(column3) , so...
Group2 AS (Select (column3 ),
COUNT (column3) as cntr
From table 2 as Count
Where (year (date_value) = 2018 and month(Date_vaLue) = 2)
Group by column2
)

Combine three columns from different tables into one row

I am new to sql and are trying to combine a column value from three different tables and combine to one row in DB2 Warehouse on Cloud. Each table consists of only one row and unique column name. So what I want to is just join these three to one row their original column names.
Each table is built from a statement that looks like this:
SELECT SUM(FUEL_TEMP.FUEL_MLAD_VALUE) AS FUEL
FROM
(SELECT ML_ANOMALY_DETECTION.MLAD_METRIC AS MLAD_METRIC, ML_ANOMALY_DETECTION.MLAD_VALUE AS FUEL_MLAD_VALUE, ML_ANOMALY_DETECTION.TAG_NAME AS TAG_NAME, ML_ANOMALY_DETECTION.DATETIME AS DATETIME, DATA_CONFIG.SYSTEM_NAME AS SYSTEM_NAME
FROM ML_ANOMALY_DETECTION
INNER JOIN DATA_CONFIG ON
(ML_ANOMALY_DETECTION.TAG_NAME =DATA_CONFIG.TAG_NAME AND
DATA_CONFIG.SYSTEM_NAME = 'FUEL')
WHERE ML_ANOMALY_DETECTION.MLAD_METRIC = 'IFOREST_SCORE'
AND ML_ANOMALY_DETECTION.DATETIME >= (CURRENT DATE - 9 DAYS)
ORDER BY DATETIME DESC)
AS FUEL_TEMP
I have tried JOIN, INNER JOIN, UNION/UNION ALL, but can't get it to work as it should. How can I do this?
Use a cross-join like this:
create table table1 (field1 char(10));
create table table2 (field2 char(10));
create table table3 (field3 char(10));
insert into table1 values('value1');
insert into table2 values('value2');
insert into table3 values('value3');
select *
from table1
cross join table2
cross join table3;
Result:
field1 field2 field3
---------- ---------- ----------
value1 value2 value3
A cross join joins all the rows on the left with all the rows on the right. You will end up with a product of rows (table1 rows x table2 rows x table3 rows). Since each table only has one row, you will get (1 x 1 x 1) = 1 row.
Using UNION should solve your problem. Something like this:
SELECT
WarehouseDB1.WarehouseID AS TheID,
'A' AS TheSystem,
WarehouseDB1.TheValue AS TheValue
FROM WarehouseDB1
UNION
SELECT
WarehouseDB2.WarehouseID AS TheID,
'B' AS TheSystem,
WarehouseDB2.TheValue AS TheValue
FROM WarehouseDB2
UNION
WarehouseDB3.WarehouseID AS TheID,
'C' AS TheSystem,
WarehouseDB3.TheValue AS TheValue
FROM WarehouseDB3
Ill adapt the code with your table names and rows if you tell me what they are. This kind of query would return something like the following:
TheID TheSystem TheValue
1 A 10
2 A 20
3 B 30
4 C 40
5 C 50
As long as your column names match in each query, you should get the desired results.

How select values where all columns are null for particular ID, ID is not unique

I have a table with following format and I want to get the LotId if Value1 is null for all the rows.
Now If I am doing Select,
Select * from Table1 where Value1 IS null , I am getting back a row .
But I want nothing should be returned as there are two rows which have some value.
I thought of self join , but this can have n number of rows.
Id LotId Value1
-------------------------------------------------
1 LOt0065 NULL
2 LOt0065 SomeValue
3 LOt0065 SomeValue
I think you'll need to use an EXISTS subquery here:
SELECT a.lotid
FROM table1 a
WHERE NOT EXISTS (
SELECT 1
FROM table1 b
WHERE b.lotid = a.lotid
AND b.value1 IS NOT NULL
);
If my syntax is right, then this will show you all records that don't have any NULL values for that lotid:
It uses a SELECT 1 because the subquery doesn't need to show any value, it just needs to match on the outer query.
You compare the table in the inner query to the table in the outer query and match on the common field you're looking at (lotid in this case)
This could also be done with a NOT IN clause.
Does this give you the result you want?

How to SQL Query records from Multiple that Equal 0?

I have a table that has multiple duplicate records in the first column (ID records), but has varying numerical data in the second column.
I want to be able to identify which ID records have 0 for all of their numerical records.
For example the table can look like:
ID Value
1 2
1 2
1 0
2 0
2 0
2 0
I would want to only identify ID 2 because all the values are equal to 0. I don't want ID 1 because there are values > 0
Sorry if this isn't formatted properly or confusing.
You might use "NOT IN":
SELECT DISTINCT Id
FROM table1
WHERE Id NOT IN (SELECT Id FROM table1 WHERE Value <> 0)
SELECT DISTINCT ID FROM TABLE
WHERE ID NOT IN (SELECT DISTINCT ID FROM TABLE WHERE VALUE <> 0)
This will take all ID in the table where there is not a row where the value is non-zero.
SELECT *
FROM table t1
WHERE NOT EXISTS (SELECT 1 FROM table t2 WHERE t2.ID = t1.id AND Value <> 0)
"Select all records whose ID is not in the set of records that have a non-zero Value."