Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5846907
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T12:38:36+00:00 2026-05-22T12:38:36+00:00

I have a complex query that joins different tables to get the count. There

  • 0

I have a complex query that joins different tables to get the count. There are a few fields to group by. Now, I want to add an additional field which needs a case statement. And this field also has to be in the group by list. My query originally looks like this –

SELECT DMAGATR.WRK_LOC_LEVEL4 
     , DMBR.WRK_LOC_NM 
     , DMBR.RELCD 
     , COUNT(DISTINCT DMBR.DMBRKEY) AS ELIG_COUNT
      FROM DMBR 
INNER JOIN DCUST DCUST ON DMBR.DCUSTKEY = DCUST.DCUSTKEY
INNER JOIN DMAGATR DMAGATR ON DMBR.DMBRKEY = DMAGATR.DMBRKEY
 LEFT JOIN DMDYNATR DMDYNATR ON DMBR.DMBRKEY = DMDYNATR.DMBRKEY
     WHERE DMBR.C_TIMESSTAMP <= '12/31/2011'
       AND DMBR.RELCD IN ('0', '1') 
       AND DMBR.EE_STS IN ( 'A','L')
       AND (DMBR.DEL_DT IS NULL
        OR DMBR.DEL_DT > '12/31/2011')
       AND DCUST.PRCD = 'TAR'
  GROUP BY DMAGATR.WRK_LOC_LEVEL4, DMBR.WRK_LOC_NM, D_MEMBER.REL_CD

But the new field looks something like this –

(SELECT CASE
          WHEN (DMBR.WRK_LOC_NM = '6' AND DMBR.GDR = 'M' AND DMBR.REL_CD in ('0','1') 
            AND DMBR.EE_STS IN ('A','L')) THEN 'SEG 1'
          ELSE 'OTHER'
        END 
   FROM DMBR) as CMPN

I tried to add it in the select list but it did not work. Then I added it in two places – in the select and also in the group by list. That did not work either.

The errors I got were:

  1. ORA-00904 – CMPN not a valid column
  2. ORACLE prepare error: ORA-22818: subquery expressions not allowed here.

I did some research online found examples that were close but not exactly identical to mine.

SQL GROUP BY CASE statement with aggregate function
Not sure if I understood the question here
SQL query with count and case statement
This is quite different from my need.
http://jerrytech.blogspot.com/2008/04/can-you-group-by-case-statement-in-sql.html
(this is close but I dont need the insert statements I tried this approach but it did not work for me)

Any suggestions would be appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T12:38:37+00:00Added an answer on May 22, 2026 at 12:38 pm

    I think the error is you are describing a FIELD (ie: result column) for the query like the others: DMAGATR.WRK_LOC_LEVEL4 ,DMBR.WRK_LOC_NM ,DMBR.RELCD ,COUNT (DISTINCT DMBR.DMBRKEY…

    I think the error is that when using a SQL-Select statement for a resulting COLUMN, it must only return a single row. Since your query is just “… FROM DMBR ) as CMPN”, you are returning more than one row for the field and no Database knows how to guess your result.

    What you are probably missing is both a WHERE clause on the field, and possibly a GROUP by if you are looking for a distinct value from within the DMBR table.

    Fix that and it should get you MUCH further along. Not knowing the rest of data structure or relationships, I can’t figure what your ultimate result is meant to be.


    ADDITIONAL COMMENT…

    By looking at other answers provided, they have offered to do an immediate CASE WHEN on whatever the current “DMBR” record you are on, which would be correct, but not quite working. I think due to the two possible results, that too will have to be part of the group by.. as count(DISTINCT), the group by has to be based on any non-aggregation columns… of which, this case/when would be as such.. So your ultimate result would have

    Lvl, Work Loc, RelCD, Case/when, count(distinct)  where...
                            SEG 1     999
                            Other     999
    

    Additionally, your CASE/WHEN had two components exactly matching your WHERE clause, so I took it out of there since no records of that set would have been returned anyway.

    So, all that being said, I would write it as…

    SELECT
          DMAGATR.WRK_LOC_LEVEL4,
          DMBR.WRK_LOC_NM,
          DMBR.RELCD,
          CASE WHEN (DMBR.WRK_LOC_NM = '6' 
                 AND DMBR.GDR = 'M' ) 
               THEN 'SEG 1'
               ELSE 'OTHER'
               END as WhenStatus,
          COUNT (DISTINCT DMBR.DMBRKEY) AS ELIG_COUNT
       FROM
          DMBR 
             JOIN DCUST 
                ON  DMBR.DCUSTKEY = DCUST.DCUSTKEY
             JOIN DMAGATR
                ON  DMBR.DMBRKEY = DMAGATR.DMBRKEY
             LEFT JOIN DMDYNATR
                ON  DMBR.DMBRKEY = DMDYNATR.DMBRKEY
       WHERE
              DMBR.C_TIMESSTAMP <= '12/31/2011'
          AND DMBR.REL_CD in ('0','1') 
          AND DMBR.EE_STS IN ('A','L')) 
          AND DCUST.PRCD = 'TAR'
          AND (    DMBR.DEL_DT IS NULL
               OR  DMBR.DEL_DT > '12/31/2011')
       GROUP BY 
          DMAGATR.WRK_LOC_LEVEL4,
          DMBR.WRK_LOC_NM,
          D_MEMBER.REL_CD,
          CASE WHEN (DMBR.WRK_LOC_NM = '6' 
                AND DMBR.GDR = 'M' ) 
              THEN 'SEG 1'
              ELSE 'OTHER'
              END
    

    Finally, sometimes, I’ve seen where a group by will choke on a complex column, such as a case / when. However, different servers allow ordinal reference to the group by (and order by too) positions. So, since the query has 4 non-aggregate columns (all listed first), then the count of distinct, you MIGHT be able to get away with changing the GROUP BY clause to…

    GROUP BY 1, 2, 3, 4

    All pertaining to the sequential order of columns STARTING the SQL-Select call.

    — CLARIFICATION about group by and case-sensitivity

    First, the case-sensitivity, most engines are case-sensitive on keywords, hence CASE WHEN … AND … THEN … ELSE … END.

    As for the “group by” (and also works for the “order by”), its more of a shortcut to the ordinal columns in your query instead of explicitly listing the long names to them and having to re-type the entire CASE construct a second time, you can just let the engine know which column of the result set you want to order by look at the following (unrelated) query…

    select
          lastname,
          firstname,
          sum( orderAmount ) TotalOrders
       from
          customerOrders
       group by
          lastname,
          firstname
       order by 
         TotalOrders DESC
    

    and

    select
          lastname,
          firstname,
          sum( orderAmount ) TotalOrders
       from
          customerOrders
       group by
          1,
          2
       order by 
          3 DESC
    

    Each would produce the same results… The fictitious customerOrders table would be pre-aggregated by last name and first name and show the total per person (all assuming no duplicate names for this example, otherwise, I would have used a customer ID). Once that is done, the order by kicks in and will put in order of the most sales to a given customer in DESCENDING order at the top of the list.

    The numbers just represent the ordinal columns being returned in the query instead of long-hand typing the field names. More for the issue you have of your “CASE/WHEN” clause to prevent oops retyping and missing it up in the group by and pulling your hair out figuring out why.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a complex query with group by and order by clause and I
I have a complex .NET Remoting server app that provides a couple of services.
I have a complex command that I'd like to make a shell/bash script of.
I have some complex stored procedures that may return many thousands of rows, and
I have a 'complex item' that is in XML, Then a 'workitem' (in xml)
Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that
I have a complex sharepoint deploy with multiple EventReceivers and Workflows. I also have
I have two complex (i.e. objects with string, int, double, List and other home
I have a complex WPF UserControl made of other ContentControl templates which contain sets
If i have a complex object, what is the best practice pattern to write

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.