Home > database >  Use results in one column on a SQL table to search another table
Use results in one column on a SQL table to search another table

Time:12-08

I was just after an elegant solution to what I'm doing rather than just manually copying and pasting into each SELECT query.

I have a list of 200 string results from one table.

SELECT name FROM accounts

Which gives me results like:

name
$string1$
$string2$

I want to then search each result in another query on another table to get a COUNT. Doing this manually one by one, I would run:

SELECT COUNT(DISTINCT table.id) FROM table WHERE table.code LIKE '%$string1$%'

I want to be lazy and achieve this via SQL if possible where I end up with something like this:

accounts.name Count
$string1$ 5699
$string2$ 245

Any advice or help would be most welcome!

CodePudding user response:

It sounds like you'd want to join on a LIKE operator, and then count the results:

  ;WITH matches_on_account_name AS (
        SELECT a.[name] AS account_name
          FROM accounts AS a
          JOIN [table] AS t ON t.[code] LIKE '%'   a.[name]   '%'
  )
  SELECT account_name,
         COUNT(*) AS num_accounts
    FROM matches_on_account_name
GROUP BY account_name;

CodePudding user response:

One option that should work on pretty much every RDBMS is a correlated subquery

select a.name, (
  select Count(*) 
    from table t 
    where t.code like Concat('%',a.name,'%')
) as Count
from accounts a

CodePudding user response:

Using CONCAT for sticking the % to the name.

And defaulting the NULL names to something unmatchable.
Just preventing that name LIKE '%%' would match everything.

SELECT 
  acc.name AS account_name
, COUNT(DISTINCT tbl.id) AS total_uniq_table_id
FROM accounts  AS acc
JOIN yourtable AS tbl
  ON tbl.code LIKE CONCAT('%',COALESCE(acc.name,'D§OUOSVAVV§M'),'%') 
GROUP BY acc.name
  •  Tags:  
  • sql
  • Related