Grouping on the date part of a datetime column

Grouping on the date part of a datetime column

What would be the easiest way to get the AVG for lic_used by date with data in a table like this:

LIC_USED   LIC_DATE
  18       10/01/02 03:00:00
  16       10/01/02 04:00:00
  24       10/02/02 03:00:00

I need to get the AVG(lic_used) for each day.


    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

The answer is to GROUP BY the date part. This means splitting out the date part without the time part. There are several ways to do this, depending on which database system you're using. For example, in Microsoft SQL/Server, you can use the CONVERT function to generate the date part, and group on that:

select avg(lic_used)
     , convert(char(8),lic_date,10)
  from yourtable
group 
    by convert(char(8),lic_date,10)

Note that I have chosen style 10 for the conversion, which is mm/dd/yy with a two-character year, but only because that's the format you used in your example. (I personally prefer yyyy-mm-dd because it's not ambiguous.) Hence with style 10 the result of the conversion is an 8-character string. Refer to the Microsoft documentation CAST and CONVERT for other styles.

For More Information


This was first published in October 2002

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.