Search code examples
kdb

Getting Month from date field - KDB


I have sales data stored in a database. The sales_date field contains the date on which the sale took place. I want to extract this data grouped by month, so that I will get the aggregate data for Jan, Feb, etc. Is there a way I can do this without having to extract the entire data and then doing it manually?


Solution

  • Something like the following should work. If the data is partitioned on disk, remember to include the partition in the where clause.

    q)tbl:([]dt:20?(2013.01.01;2013.02.01;2013.01.03);sales:20?100000)
    q)select sum sales by `month$dt from tbl
    dt     | sales
    -------| ------
    2013.01| 701075
    2013.02| 298200
    q)select avg sales by `month$dt from tbl
    dt     | sales
    -------| --------
    2013.01| 50076.79
    2013.02| 49700