title: SQL-Case / Cannot perform an aggregate function on an expression containing an aggregate or a subquery
body: <p>Here's my code, which I'm trying to get working:</p>
  
  <pre><code>DECLARE @DATE AS SMALLDATETIME ,
      @BasTar DATE ,
      @Bittar DATE 
  
  SET @DATE = GETDATE() - 1
  SET @BasTar = GETDATE() - 1
  SET @Bittar = GETDATE() - 1
  
  
  SELECT  ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                          THEN ( TS.DEFAULT_RETURN_PRICE )
                     END), 0) AS SATIST ,
          ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                          THEN ( TS.VAT_TOTAL )
                     END), 0) AS SATISIV ,
          ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                          THEN ( TS.DEFAULT_RETURN_PRICE )
                     END), 0) AS IADET ,
          ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                          THEN ( TS.VAT_TOTAL )
                     END), 0) AS IADEIV ,
          ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                               AND TH.STATUS = 0 THEN TS.AMOUNT
                     END), 0) AS SATISMIK ,
          ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                               AND ST.ID IN ( SELECT  ID
                                              FROM    FLO_AA_MAGAZALAR )
                               AND TH.STATUS = 0 THEN TS.AMOUNT
                     END), 0) AS IADEMIK
  FROM    TRANSACTION_HEADER TH WITH ( NOLOCK )
          INNER JOIN TRANSACTION_SALE TS WITH ( NOLOCK ) ON TS.FK_TRANSACTION_HEADER = TH.ID
          INNER JOIN STORE ST WITH ( NOLOCK ) ON ST.ID = TH.FK_STORE
                                                 AND ST.NUM BETWEEN '3999' AND '9999'
  WHERE   TH.STATUS = 0
          AND ST.DESCRIPTION NOT LIKE 'POL_%'
          AND ST.DESCRIPTION NOT LIKE 'SIS%'
          AND CONVERT(CHAR(11), TH.TRANS_DATE, 103) BETWEEN @BasTar
                                                    AND     @Bittar
  </code></pre>
  
  <p>So because I use <code>ST.ID IN(SELECT ID FROM FLO_AA_MAGAZALAR)</code> in the case statement, it gives me that error for each sum(case) statement.</p>
  
  <blockquote>
    <p>Cannot perform an aggregate function on an expression containing an aggregate or a subquery. </p>
  </blockquote>