Please see the SQL query I have.
select
CASE
WHEN (SELECT COUNT(COL1) FROM FACT_ACTIVITY group BY FACT_ACTIVITY.COL2)>1
THEN (SELECT COUNT(COL3) FROM FACT_ACTIVITY)
WHEN (SELECT COUNT(COL1) FROM FACT_ACTIVITY group BY FACT_ACTIVITY.COL2)=1
THEN (SELECT COUNT(COL4) FROM FACT_ACTTIVITY)
END
,EXTRACT(year from fa.INC_START_DATETIME) AS YearOFF
,COUNT(fa.COL2) AS OffCount from FACT_ACTIVITY fa INNER JOIN
DIM_OFF_TYPE do ON fa.OFF_TYPE_ID = do.OFF_TYPE_ID
WHERE fa.OFF_TYPE_ID IN (24001) and YEAR(fa.INC_START_DATETIME) IN (2016,2017)
group by do.OFF_TYPE_DESCR,YEAR(fa.INC_START_DATETIME)
The subquery in case WHEN gives a lot of rows, but I want the subquery do the check for each FACT_ACTIVITY_ID and see if the count(col2) >1 and do the THEN statement.
1条答案
按热度按时间e5njpo681#
For the sub-queries to return one row for each FACT_ACTIVITY_ID, you have to put that filter in the WHERE clause:
Note the table alias to table FACT_ACTIVITY "fa2" in the sub-queries to distinguish between FACT_ACTIVITY in the subquery vs. FACT_ACTIVITY in the outer main query.
Also note the readability and maintainability with good white space and tabbing :)