How can I make “month” columns in Sql?

后端 未结 6 842
轻奢々
轻奢々 2020-12-17 01:44

I\'ve got a set of data that looks something like this (VERY simplified):

productId    Qty   dateOrdered
---------    ---   -----------
       1             


        
6条回答
  •  猫巷女王i
    2020-12-17 02:13

    try this. So this code will select data within certain time range, then convert it to a new column. For example, in my sql code: it selects time range between '2014-10-01' and '2014-10-31' from column 'L_dt', then create a new column called "October". In this way, we can lay out data at different columns originated from one column.

    select 
    sum(case when L_dt between '2014-10-01' and '2014-10-31' then 1 else 0 end) October,
    sum(case when L_dt between '2014-11-01' and '2014-11-30' then 1 else 0 end) November,
    sum(case when L_dt between '2014-12-01' and '2014-12-31' then 1 else 0 end) December
    from Table; 
    

    If the input looks like: L_dt
    2014-10-13 2014-12-21 2014-11-22 2014-10-10

    Then the output will be

    +---------+----------+----------+
    | October | November | December |
    +---------+----------+----------+
    |    2    |    1     |    1     |
    +---------+----------+----------+
    

提交回复
热议问题