4

I have a very simple SQL question. I have a database table with the following columns:

  1. Part Number

  2. Sales Type (for simplicity, call it Sales Type 1,2,3,4,5)

I am hoping to write a query that gives the following three columns:

  • The part number
  • The total number of sales for Sales Type = 2
  • The total number of sales for Sales Type <> 2

I can easily get two of the three columns to display with code similar to the code below but I'm stumped on how to get all three to show up at the same time.

SELECT 
    PartNumber AS PartNumber,
    COUNT(*) AS SalesCount
FROM 
    SalesTable
WHERE 
    SalesType = 2
GROUP BY 
    I.PartNumber

I'm guessing this may be very easy - I'm a SQL noob and this is my first post!

Any help is greatly appreciated!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Zak Fischer
  • 151
  • 1
  • 8

4 Answers4

2

It sounds like what you're looking for is a conditional count

SELECT 
    PartNumber, 
    SUM(CASE WHEN SalesType = 2 THEN 1 ELSE 0 END) as SaleTypeTwoCount,
    SUM(CASE WHEN SalesType <> 2 THEN 1 ELSE 0 END) as SalesOtherCount
FROM 
    SalesTable
GROUP BY
    PartNumber
Zooby
  • 325
  • 1
  • 7
1

Untested, but you want something like this:

 SELECT PartNumber, sum(case when SalesType=2 then 1 else 0) as Type2SalesCount,
    sum(case when SalesType<>2 then 1 else 0) as NoNType2SalesCount
    FROM SalesTable
    Group by PartNumber
user8834780
  • 1,620
  • 3
  • 21
  • 48
  • Perfect - thanks!!! This did it (I did have to add an END ... else 0 END). But this was exactly what I was looking for --- thank you so much!! – Zak Fischer Nov 29 '17 at 04:39
0

Haven't actually run it, but something like this should work...

SELECT
    PartNumber,
    COUNT(CASE WHEN SalesType = 2 THEN 1 END) Count2,
    COUNT(CASE WHEN SalesType <> 2 THEN 1 END) CountNot2
FROM
   SalesTable
GROUP BY
   PartNumber;

Note that COUNT(expression) only counts non-NULLs, while COUNT(*) counts all rows.

The...

CASE WHEN SalesType = 2 THEN 1 END

...is equivalent to...

CASE WHEN SalesType = 2 THEN 1 ELSE NULL END

...and will result in NULL when SalesType <> 2, which is not counted.

Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167
0

You can use case for example: saletype= case when saletype == 2 then count(saletype) when saletype <> 2 then count(saletype)

Lupitha Yañez C.
  • 354
  • 1
  • 2
  • 7