Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

sql server - SQL JOIN two tables using two condition and partial match

Let's imagine that there are two tables with independent data.

T1
Name                      Value    Time
----------------------------------------
equipment.hour.01         10       12:00:00.000     
equipment.hour.02         12       13:00:00.000 
equipment.hour.05         20       15:00:00.000 
equipment.hour.07         01       15:00:00.000 

T2
Name                      Value    Time
----------------------------------------
total.count.01         3       12:04:30.456     
total.count.02         5       13:06:01.324 
total.count.05         6       15:20:56.268 
total.count.07         8       15:40:12.570 

I want to get a column as Fault Count from second tables as follows using join clause.

Name    Value    Fault Count
--------------------------------
01      10       3
02      12       5
05      20       6
07      01       8

I want the device value and alarm numbers at the same time. I wrote a query for this, but could not solve the errors that came with not getting what I wanted. I don't know exactly where I went wrong. Can you help me?

select a.Name,a.Value,b.[Fault Count] from
(SELECT
 REVERSE(PARSENAME(REPLACE(REVERSE(t1.Name), ',', '.'), 4)) as 'Name', 
 dbo.t1.Value,
 dbo.t1.Time
   from t1 ) as a
JOIN 
(SELECT
 REVERSE(PARSENAME(REPLACE(REVERSE(t2.Name), ',', '.'), 4)) as 'Name', 
 t2.Value as 'Fault Count',
 t2.Time
   from dbo.t1 ) as b
   ON
   a.Name = b.Name and datepart('hour',a.Time) = DATEPART('hour',b.Time)
question from:https://stackoverflow.com/questions/65887626/sql-join-two-tables-using-two-condition-and-partial-match

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just extract the last two characters and join:

select right(t1.name, 2) as name, t1.value, t2.value as fault_count
from t1 join
     t2
     on right(t1.name, 2) = right(t2.name, 2);

Notes:

  • In the sample data, the resulting names are unique. If there are duplicates, you might need aggregation.
  • In the sample data, the resulting names are in both tables. This returns only names that are in both. If you want names that are missing from one of the tables, then use an outer join of some sort.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...