How do I get opposite value to COUNT(NULLIF(x,y))

Posted on 2009-04-24
Last Modified: 2012-05-06

I've got a stored procedure which has retrieved a year's worth of order history and has added an analysis code to each line.

Simplistically the table looks like ...

ID, ProductCode, Analysis

I want a result set of

ProductCode, Count(*), count where analysis = 'A', count where analysis = 'B', count where analysis = 'C', count of unanalyzed.

I've got ...

COUNT(NULLIF(Analysis, 'NONIOC/Acc/Unit')) AS [NONIOC/Acc/Unit]

but I want the number of NONIOC/Acc/Unit...

COUNT(*) - COUNT(NULLIF(Analysis, 'NONIOC/Acc/Unit')) AS [NONIOC/Acc/Unit]

gives me that. But is there a more succinct way?

I also need to do SUM()s for AnalysisValue for each of my Analysis.

Using Microsoft SQL Server 2005
Question by:RQuadling
    LVL 142

    Accepted Solution

    the CASE statement might be what you are looking for
    , SUM( CASE WHEN Analysis = 'NONIOC/Acc/Unit' THEN 1 ELSE 0 END) AS [NONIOC/Acc/Unit]
    , SUM( CASE WHEN Analysis = 'NONIOC/Acc/Unit' THEN 0 ELSE 1 END) AS [NOT NONIOC/Acc/Unit]

    Open in new window

    LVL 40

    Author Comment

    Aha! Yes.

    I thought I tried that. Seems I get my syntax all messedup.


    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
    Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
    Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now