Search code examples
sqlsql-serverselectgroup-byhaving

Querying a table with no Key field


We have a table that is storing Sales History for Part numbers by Branch. Part #s can exist in one, or many Branches. Columns include the Current month, and 3 previous months. I need to write a SELECT query that will list all the Part #s that have zero Sales History in ALL Branches. Using the sample data I provided, my query should return Part# 56789, but not Part # 12345, as it has sales in the SalesHist02 column. I should note that our actual table has over 290K unique part numbers, and over 1.3 million rows. Thanks in advance.

Sample Table Data


Solution

  • Based on your current description and sample output, you can use the HAVING clause:

    select partno
    from sales
    group by partno
    having sum(saleshistcurrmo + saleshist02 + saleshist03 + saleshist04) = 0