SQL Server : select column with 3 matching characters - sql

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;

Related

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.

SQL - Select from column A based on values in column B

Lets say I have a table with 2 columns (a, b) with following values:
a b
--- ---
1 5
1 NULL
2 NULL
2 NULL
3 NULL
My desired output:
a
---
2
3
I want to select only those distinct values from column a for which every single occurrence of this value has NULL in column b. Therefore from my desired output, "1" won't come in because there is a "5" in column b even though there is a NULL for the 2nd occurrence of "1".
How can I do this using a TSQL query?
If I understand correctly, you can do this with group by and having:
select a
from t
group by a
having count(b) = 0;
When you use count() with a column name, it counts the number of non-NULL values. Hence, if all values are NULL, then the value will be zero.
It's fairly simple to do:
SELECT A
FROM table1
GROUP BY A
HAVING COUNT(B) = 0
Grouping by A results in all the rows where the value of A is identical to be transferred into a single row in the output. Adding the HAVING clause enables to filter those grouped rows with an aggregate function. COUNT doesn't count NULL values, so when it's 0, there are no other values in B.
Two more ways to do this:
SELECT a
FROM t
EXCEPT
SELECT a
FROM t
WHERE b IS NOT NULL ;
This would use an index on (a, b):
SELECT a
FROM t
GROUP BY a
WHERE MIN(b) IS NOT NULL ;
Try it like this:
DECLARE #tbl TABLE(a INT, b INT);
INSERT INTO #tbl VALUES(1,5),(1,NULL),(2,NULL),(2,NULL),(3,NULL);
--Your test data
SELECT * FROM #tbl;
--And this is what you want - hopefully...
SELECT DISTINCT tbl.a
FROM #tbl AS tbl
WHERE NOT EXISTS(SELECT * FROM #tbl AS x WHERE x.a=tbl.a AND b IS NOT NULL)
To turn your question on it's head, you want the values from column a where there are no non-null values for that value in column b.
select distinct a
from table1 as t1
where 0 = (select count(*)
from table1 as t2
where t1.a = t2.a
and b is not null)
Sample fiddle is here: http://sqlfiddle.com/#!6/5d1b8/1
This should do it:
SELECT DISTINCT a
FROM t
WHERE b IS NULL
AND a NOT IN (SELECT a FROM t WHERE b IS NOT NULL);

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."

Compare string data between two tables

i have two tables TABLE 1 with columns
ID Text email ID
============================
1 This is Test 123#g.com
2 Make my day 1234#g.com
TABLE 2 with one column
words(column)
=============
Test
trip
day
now wat i want to do is compare the text ( each and every word) from Table 1 with each row ow word in TABLE 2, if found then the id should be logged on a different table.
example: if from TABLE1 Test is the word which is the row value in the TABLE 2 word column. so it should log ID =1 in a different table.
also once the word is found it shouldn't go for further iteration.
try this:
select *
from TABLE1
join
TABLE2
on ' '+Text+' ' like '% '+words+' %'
SQL fiddle demo
This works
SELECT t1.*,t2.words
FROM Table1 t1
JOIN Table2 t2
ON PATINDEX('%' + t2.words + '%',t1.text)>0
Output
ID Text email_ID words
1 This is Test 123#g.com Test
2 Make my day 1234#g.com day
You can to use CHARINDEX function:
select *
from TABLE1 t1
where exists
(
select 1
from TABLE2 t2
where CHARINDEX(t2.words,t1.text)>0
)
Link to documentation.