0

I am new in SQL. I would like to have a query that returns values which have multiple columns in common

I have t_table with:

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

I would like to return filenames with start and stop columns in common and name is like '%AAAA%' (2 first rows) CCCC% has the same start and stop but name isn't like '%AAAA%

I've tried with these answer Find rows that have the same value on a column in MySQL but I couldn't get the result expected. With :

SELECT  filename ,
        start
FROM    t_table
WHERE   ( start IN ( SELECT start
                     FROM   t_table
                     GROUP BY start
                     HAVING COUNT(*) > 1 ) )
        AND ( filename LIKE '%AAAA%' );

I've obtained all of them ...

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

Instead of :

           filename               |    start            |    stop
 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | 2016-12-24 00:00:00 | 2016-01-03 00:00:00
 AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBB | 2016-12-24 00:00:00 | 2016-01-03 00:00:00

Could you please help me ?

2
  • 2
    You should show more sample data along with expected output, but in any case I attempted an answer below. Commented Sep 15, 2016 at 8:17
  • Does a long, tedious filename help to explain the problem? Commented Sep 15, 2016 at 8:44

1 Answer 1

3
SELECT t1.filename,
       t1.start,
       t1.stop
FROM t_table t1
INNER JOIN
(
    SELECT start, stop            -- this subquery identifies all start, stop
    FROM t_table                  -- pairs for which 2 or more records share
    GROUP BY start, stop          -- those values
    HAVING COUNT(*) > 1
) t2
    ON t1.start = t2.start AND
       t1.stop  = t2.stop
WHERE t1.filename LIKE '%AAAA%'   -- filename contains 'AAAA'

Demo here:

SQLFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

@ali Please check the Fiddle. I only get two records from my query, not three.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.