How to use a sum (case) into second table as condition - sql

This is my query:
select matricule,nom_ligne,count(num_ticket) as nbre_ticket, sum(prix) as moant,receveur, nom_gie,
(SELECT SUM(CASE WHEN depense.id_bus = 1 THEN depense.montant ELSE 0 END) AS NbrARRNP from depense) as tot,
receveur, nom_gie from journal_recettes
group by matricule,nom_ligne,receveur, nom_gie
And I obtain this results:
Results
But what I need is to use this condition :
CASE WHEN depense.id_bus = journal_recettes.id_bus THEN depense.montant ELSE 0 END
But When I try, i obtain this error :
Error

Consider modifying your query like below by joining both tables on id_bus column
select j.matricule,
j.nom_ligne,
count(j.num_ticket) as nbre_ticket,
sum(j.prix) as moant,
j.receveur,
j.nom_gie,
SUM(d.id_bus) AS NbrARRNP
from journal_recettes j
join depense d on d.id_bus = j.id_bus
group by j.matricule,
j.nom_ligne,
j.receveur,
j.nom_gie;

You are looking for a correlated subquery. This is usually handled in the where clause:
select matricule, nom_ligne, count(num_ticket) as nbre_ticket,
sum(prix) as moant, receveur, nom_gie,
(select SUM(d.montant) AS NbrARRNP
from depense d
where d.id_bus = jr.id_bus
) as tot,
receveur, nom_gie
from journal_recettes jr
group by matricule, nom_ligne, receveur, nom_gie;
In this case, you may have an issue because the correlation condition is not a group by key. I'm not sure if Postgres supports this construct. If this is a problem, the simplest solution is to include id_bus in the group by, but without sample data, I'm not sure if that works in this case.

Assuming you are doing the join on id_bus, you can use Common Table Expressions (http://www.postgresql.org/docs/9.5/static/queries-with.html)
with sums as (SELECT id_bus, sum(CASE
WHEN depense.id_bus = 1 THEN depense.montant
ELSE 0
END) AS NbrARRNP
FROM depense
group by id_bus)
SELECT matricule,
nom_ligne,
Count(num_ticket) AS nbre_ticket,
Sum(prix) AS moant,
receveur,
nom_gie,
d.NbrARRNP AS tot,
receveur,
nom_gie
FROM journal_recettes j left outer join sums d on j.id_bus = d.id_bus
GROUP BY matricule,
nom_ligne,
receveur,
nom_gie,
j.id_bus

Many thanks to all.
I post my final solution to contribute :
select p1.matricule,p1.nom_ligne,
Count(p1.num_ticket) as nbre_ticket, Sum(p1.prix) as montant,
(select sum(montant) as tot from depense p2
where date_trunc('day',p2.date_depense) = date_trunc('day',p1.date_vendu)
group by date_depense) som_depense ,
(Sum(p1.prix) -((select sum(montant) as tot from depense p3
where date_trunc('day',p3.date_depense) = date_trunc('day',p1.date_vendu)
group by date_depense) ) ) net_reverse ,to_char(p1.date_vendu,'YYYYMMDD'),
p1.receveur, p1.nom_gie, id_line
from journal_recettes p1
group by
matricule,nom_ligne, date_vendu,receveur,nom_gie, id_line
And it's work as well.

Related

Group by + Select Case

I try to query this code but i got the error massage.
"ORA-00979: not a GROUP BY expression"
Can we use case SUM and Max in group by function.
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Can we use case SUM and Max in group by function.
Yes
However, your problem is that you use PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD = 'OUT-P' inside the CASE expression and neither PROCESSMASTER.COMP_FLG nor PROCESS.MED_PROC_CD are in the GROUP BY clause or inside of an aggregation function.
You either want:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD,
PROCESSMASTER.COMP_FLG, -- Add to the group by clause
PROCESS.MED_PROC_CD -- Add to the group by clause
;
or something like:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
CASE
WHEN MAX(PROCESSMASTER.COMP_FLG) = 1
AND COUNT(CASE WHEN PROCESS.MED_PROC_CD = 'OUT-P' THEN 1 END) > 0
THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Note: this is untested as you have not provided a minimal representative example of your tables or data to test against.

Inner join with count in select query

I am trying to get the query for details along with the status if the particular column exists for that report using the below query.
select rh.Rec_ID
,rh.Report_ID
,rh.Report_Name
,rh.Source_Type_Display
,rh.Description
,rh.IndID
,rh.Name
,rh.Time_Updated
,count(*) OVER() as TotalCount
,case when count(rd.demo) > 0 THEN 'Completed' ELSE 'incomplete' END
FROM v_Report_Header_OV rh
inner join v_Table_NI_Report_Demo rd
ON rh.Report_ID = rd.Report_ID
WHERE rh.Client_ID = 12324
I am getting below error
Column 'v_Report_Header_OV.Rec_ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I am not sure why i am getting error, Could any one please help on this
Many thanks in advance.
you missed group by
select rh.Rec_ID
,rh.Report_ID
,rh.Report_Name
,rh.Source_Type_Display
,rh.Description
,rh.IndID
,rh.Name
,rh.Time_Updated
,count(*) OVER() as TotalCount
,case when count(rd.demo) > 0 THEN 'Completed' ELSE 'incomplete' END
FROM v_Report_Header_OV rh
inner join v_Table_NI_Report_Demo rd
ON rh.Report_ID = rd.Report_ID
WHERE rh.Client_ID = 12324
group by rh.Rec_ID
,rh.Report_ID
,rh.Report_Name
,rh.Source_Type_Display
,rh.Description
,rh.IndID
,rh.Name
,rh.Time_Updated

SQL Combining Two Totally seperate tables to one

I am VERY new to SQL and self taught. I have two SQL that I stuggled through but got working. Now I need to combine them into one and I'm lost.
SELECT
s.lastfirst,
s.student_number,
SUM(tr.howmany)
FROM
students s
JOIN
truancies tr ON s.id = tr.studentid
WHERE
s.enroll_status = 0 AND
s.schoolid = ~(curschoolid)
GROUP BY
s.lastfirst, s.student_number
HAVING
SUM(tr.howmany) > 0
ORDER BY
s.lastfirst
And this table:
SELECT
S.DCID as DCID,
S.LASTFIRST as LASTFIRST,
S.STUDENT_NUMBER as STUDENT_NUMBER,
S2.FC_SRVC_HRS_DUE as FC_SRVC_HRS_DUE,
CASE
WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
THEN '0'
ELSE S2.FC_SRVC_HRS_COMPLETED
END AS FC_SRVC_HRS_COMPLETED,
S2.FC_SRVC_HRS_BUYOUT as FC_SRVC_HRS_BUYOUT,
CASE
WHEN S2.FC_SRVC_HRS_COMPLETED IS NULL
THEN S2.FC_SRVC_HRS_DUE * S2.FC_SRVC_HRS_BUYOUT
ELSE ((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT)
END as Balance_Due
FROM
STUDENTS S, U_STUDENTSUSERFIELDS S2
WHERE
S.DCID = S2.STUDENTSDCID AND
s.enroll_status = 0 AND
s.schoolid = ~(curschoolid) AND
(((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) > 0 OR
((S2.FC_SRVC_HRS_DUE - S2.FC_SRVC_HRS_COMPLETED) * S2.FC_SRVC_HRS_BUYOUT) IS NULL) AND
S2.FC_SRVC_HRS_DUE >.1
ORDER BY
s.lastfirst
What I am really looking for are the totals of both of these. I want the SUM(tr.howmany) from the first table and the balance due of the second BUT I need the filters that are in there. This would be sorted by student. I hope I am making sense. Any assistance would be appreciated.
You can join together 2 separate SQL select statements:
Eg:
Select A.id, A.value, B.value
From (select id, count(*) as value from TableA ...) AS A
join (select id, sum(field) as value from TableB ...) AS B
on A.id = B.id
order by A.id
As long as you have a common field to join on this would work. In your case the student_number looks like a good candidate. You will have to do the ordering outside of your subqueries.

How to replace a NULL when a COUNT(*) returns NULL in DB2

I have a query:
SELECT A.AHSHMT AS SHIPMENT, A.AHVNAM AS VENDOR_NAME, D.UNITS_SHIPPED, D.ADPON AS PO, B.NUMBER_OF_CASES_ON_TRANSIT, C.NUMBER_OF_CASES_RECEIVED FROM AHASNF00 A
INNER JOIN (SELECT IDSHMT, COUNT(*) AS NUMBER_OF_CASES_ON_TRANSIT FROM IDCASE00 WHERE IDSTAT = '01' GROUP BY IDSHMT) B
ON (A.AHSHMT = B.IDSHMT)
LEFT JOIN (SELECT IDSHMT, (COUNT(*) AS NUMBER_OF_CASES_RECEIVED FROM IDCASE00 WHERE IDSTAT = '10' GROUP BY IDSHMT) C
ON (A.AHSHMT = C.IDSHMT)
INNER JOIN (SELECT ADSHMT, ADPON, SUM(ADUNSH) AS UNITS_SHIPPED FROM ADASNF00 GROUP BY ADSHMT, ADPON) D
ON (A.AHSHMT = D.ADSHMT)
WHERE A.AHSHMT = '540041134';
On the first JOIN statement I have a COUNT(*), on this count sometimes I will get NULL. I need to replace this with a "0-zero", I know think I know how to do it in SQL
ISNULL(COUNT(*), 0)
But this doesn't work for DB2, how can I accomplish this? All your help is really appreciate it.
Wrap a COALESCE around each of the nullable totals in your SELECT list:
SELECT A.AHSHMT AS SHIPMENT,
A.AHVNAM AS VENDOR_NAME,
COALESCE( D.UNITS_SHIPPED, 0 ) AS UNITS_SHIPPED,
D.ADPON AS PO,
COALESCE( B.NUMBER_OF_CASES_ON_TRANSIT, 0 ) AS NUMBER_OF_CASES_ON_TRANSIT,
COALESCE( C.NUMBER_OF_CASES_RECEIVED, 0 ) AS NUMBER_OF_CASES_RECEIVED
FROM ...
The inner joins you're using for expressions B and D mean that you will only receive rows from A that have one or more cases in transit (expression B) and have one or more POs in expression D. Is that the way you want your query to work?
Instead of using ISNULL(COUNT(*), 0),
try using COALESCE(COUNT(*),0)
use IFNULL(COUNT(*), 0) for DB2

SQL query using a case statement within the group by fields

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:
ORA-00904 - CMPN not a valid column
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.
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.
You can also try this (derived subquery) approach if the other answers don't work:
SELECT
WRK_LOC_LEVEL4,
WRK_LOC_NM,
RELCD,
CMPN,
COUNT (DISTINCT DMBRKEY) AS ELIG_COUNT
FROM
( 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 CMPN,
DMBR.DMBRKEY
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')
) AS TMP
GROUP BY
WRK_LOC_LEVEL4,
WRK_LOC_NM,
REL_CD,
CMPN
I don't know exactly what you meant by "in the SELECT list". I don't know why CMPN includes its own SELECT. Are you trying to do the following, and if not, what different is the goal?
SELECT
DMAGATR.WRK_LOC_LEVEL4
,DMBR.WRK_LOC_NM
,DMBR.RELCD
,COUNT (DISTINCT DMBR.DMBRKEY) AS ELIG_COUNT
,(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
) as CMPN
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
,(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)
SELECT
DMAGATR.WRK_LOC_LEVEL4
,DMBR.WRK_LOC_NM
,DMBR.RELCD
,COUNT (DISTINCT DMBR.DMBRKEY) AS ELIG_COUNT,
(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
) as CMPN
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, DMBR.GDR, DBMR.EE_STS