Skip to content
Advertisement

How can I get a query displayed monthly with a subquery

I have a query here with a subquery. This shows me the complete result for the year. How do I get it to be displayed to me on a monthly basis. I’ve tried a few things but always get an error message

Here my query

SELECT 
    masch_nr, SUM(dauer) AS Prozess_Verfügbarkeit,
    (SELECT SUM(dauer)
     FROM [hydra1].[hydadm].[ereignis]
     WHERE YEAR(begin_ts) = YEAR(CURRENT_TIMESTAMP)
       AND masch_nr = 'FIMI1'
       AND bmktonr IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11')) AS Verfügbarkeit
FROM 
    [hydra1].[hydadm].[ereignis]
WHERE 
    YEAR(begin_ts) = YEAR(CURRENT_TIMESTAMP)
    AND masch_nr = 'FIMI1'
    AND bmktonr IN ('7', '11')
GROUP BY 
    masch_nr

The result should look like this:

Month | Prozess_Verfügbarkeit | Verfügbarkeit
------+-----------------------+--------------
 1    |         344           |     4556
 2    |         445           |     5654

Thank you

Advertisement

Answer

You can probably simplify this by using conditional aggregation

SELECT 
  YEAR(begin_ts) AS [Year] 
, MONTH(begin_ts) AS [Month] 
, masch_nr
, SUM(CASE WHEN bmktonr IN ('7', '11') 
      THEN dauer END) AS Prozess_Verfügbarkeit
, SUM(CASE WHEN bmktonr IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11') 
      THEN dauer END) AS Verfügbarkeit
FROM [hydra1].[hydadm].[ereignis]
WHERE masch_nr = 'FIMI1'
  AND begin_ts >= DATEADD(YEAR,DATEDIFF(YEAR,0,CURRENT_TIMESTAMP),0)
  AND begin_ts <  DATEADD(YEAR,DATEDIFF(YEAR,0,CURRENT_TIMESTAMP)+1,0)
GROUP BY YEAR(begin_ts), MONTH(begin_ts), masch_nr
ORDER BY [Year], [Month], masch_nr
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement