SQL Server - Matrix of multiple WHERE queries

If I have a table like below:


Source  Event           Date        Qty
Site A  Create Account  5/05/2018   6
Site B  Create Account  4/05/2018   12
Site A  Update Account  6/05/2018   1
Site A  Update Notes    7/05/2018   2
Site B  Add Dependant   5/05/2018   1
Site C  Create Account  5/05/2018   14

And another like this:


Date        OrdersRec
4/05/2018   162
5/05/2018   123
6/05/2018   45
7/05/2018   143

And want to build a sort of matrix table to be able to use again and again for various date ranged queries, like this:


Date        Create  Update  UpdateNotes AddDependant    OrdersRec
4/05/2018   12      0       0           0               162
5/05/2018   20      0       0           1               123
6/05/2018   0       1       0           0               45
7/05/2018   0       0       2           0               143

What would be the best way of doing so?


I started with an INSERT into for the dates and the CreateAccount numbers, but I'm not sure how to go back and update the other counts for particular dates, or even if thats stupid and I'm missing something obvious.



2 个解决方案



Just use union all or join. There is no reason to create a new table for this:

只需使用union all或join。沒有理由為此創建一個新表:

select date, sum(v_create) as v_create, sum(v_update) as v_update,
       sum(v_updatenotes) as v_updatenotes, sum(v_adddependent) as v_adddependent,
       sum(orderrec) as orderec
from ((select t1.date, v.*, 0 as OrdersRec
       from table1 t1 cross apply
            (values ( (case when event = 'Create Account' then quantity else 0 end),
                      (case when event = 'Update Account' then quantity else 0 end),
                      (case when event = 'Update Notes' then quantity else 0 end),
                      (case when event = 'Add Dependent' then quantity else 0 end)
             ) v(v_create, v_update, v_updatenotes, v_adddependent)
      ) union all
      (select date, 0, 0, 0, 0, orderrec
       from table2
     ) t
group by date
order by date;

This handles a lot of edge cases, such as when dates are missing from one or the other tables.




Why don't you create a variable table having all the dates, and use it as your main table.


Then you would so something like this


select m.date,
sum(case when event = 'Create Account' then 1 else 0) as create,
sum(case when event = 'Update Account' then 1 else 0) as updates,
sum(o.ordersrec) as orders
from @main as m
       inner join @orders as o on o.date = m.date
       inner join @events as e on e.date = m.date
group by m.date



粤ICP备14056181号  © 2014-2021 ITdaan.com