Search code examples
mysqlsqldatabasedata-analysis

What SQL query can I use to select users with only 0 products?


I am inserting a CSV file with a large amount of data in a similar format to the screenshot below.

I'm currently trying to create an SQL query that will select all users with:

  • 0 in the 'Data' column (Column E)
  • 0 in the 'Min' column (Column F)
  • 1 in the 'Amt' column (Column G)
  • All 3 of the above need to be true for every row of that user.

So, if the query was ran on the data below only 'Steven Jones' would be selected & not 'Alice Baker' because 'Steven Jones' is the only user where all of his rows have the 0, 0, 1 I am looking for.

The SQL database consists of one table with the field names below.

Could anybody point me in the correct direction for creating the query? Thank you.

Screenshot of CSV


Solution

  • Use having and group by:

    select userId
    from table t
    group by userId
    having min(data) = 0 and max(data) = 0 and
           min(`min`) = 0 and max(`min`) = 0 and
           min(amt) = 1 and max(amt) = 1;