Domanda

I am using the below stored procedure in order to combine multiple counts. This works fine so far and returns the following XML, i.e. a count of records for each of the last 6 months.

As I am pretty new to SQL and all these counts are done on the same table I was wondering if there is a better / faster way to achieve the same.

Example result (XML):

<ranks>
  <groupCount>18</groupCount>
  <groupCount>15</groupCount>
  <groupCount>21</groupCount>
  <groupCount>13</groupCount>
  <groupCount>15</groupCount>
  <groupCount>19</groupCount>
</ranks>

My stored procedure:

BEGIN
    SET NOCOUNT ON;
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '01', 112)
        UNION ALL
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -1, GETDATE()), 112) + '01', 112)
        UNION ALL
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -2, GETDATE()), 112) + '01', 112)
        UNION ALL
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -3, GETDATE()), 112) + '01', 112)
        UNION ALL
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -4, GETDATE()), 112) + '01', 112)
        UNION ALL
    SELECT      COUNT(*) AS groupCount
    FROM        Log_PE
    WHERE       CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -5, GETDATE()), 112) + '01', 112)

    FOR XML PATH(''), ROOT('ranks')
END

Many thanks for any help with this, Tim.

È stato utile?

Soluzione

Your requirements seem to conflict with what you are doing in your SQL

select CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '01', 112)

will get the first day of the current month

select CONVERT(DATE, CONVERT(VARCHAR(6), GETDATE(), 112) + '02', 112)

will get the second day of the current month

To get the count of the last 6 complete months of records grouped by month

SELECT      COUNT(*) AS groupCount
     FROM        Log_PE
     WHERE       dateEsc >= CAST(DATEADD(day, 1, DATEADD(month, -6, DATEADD(day, day(GETDATE())*-1, GETDATE()))) as DATE) --the first day of the month, 6 months ago
        AND dateEsc < DATEADD(day, (day(GETDATE())*-1)+1, GETDATE()) -- the first day of current month
     GROUP BY year(dateEsc), month(dateEsc)
     ORDER BY year(dateEsc), month(dateEsc)
     FOR XML PATH(''), ROOT('ranks')

Here is a SQL Fiddle: http://www.sqlfiddle.com/#!3/3ff71/7

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top