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.

我開始使用INSERT進入日期和CreateAccount數字,但我不知道如何返回並更新特定日期的其他計數,或者即使那些愚蠢而且我遺漏了一些明顯的東西。

Thanks!

2 个解决方案

#1


1  

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.

這會處理許多邊緣情況,例如當一個或另一個表中缺少日期時。

#2


0  

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