2014-03-30 24 views
1

我有这个表...TSQL:和之前和之后的今天按客户

TABLE [orders] (
    [customer_ID] uniqueidentifier, 
    [salary] money, 
    [enter_into_force_date] date 
) 

我需要按“CUSTOMER_ID”和今天之前的工资总和(enter_into_force_date < = GETDATE)和工资今天之后的总和(enter_into_force_date> getdate) - 也就是说,我需要知道每个客户,我们到目前为止的薪水总额以及未来的薪水。

所以结果应该像...

customer_ID       before_today after_today 
7FBF73B0-6F18-488B-8BEA-CB1968473BBE  20,100.00 10,211.00 
679329F5-D7BB-44BE-9E76-F2F02DE5FD00  1,500.10 30.100,10 

我怎么会做出这样的TSQL?

回答

4

您可以使用此查询

select customer_id, 
    sum(case when enter_into_force_date <= GETDATE() then salary else 0 end) before_today, 
    sum(case when enter_into_force_date <= GETDATE() then 0 else salary end) after_today 
from orders 
group by customer_id 
+1

完美..感谢了很多 - 我已经学到新的东西今天...谢谢。 :) – MojoDK

+1

+1。 。 。我想指出的是,使用相同的条件并交换'then'和'else'子句可确保'NULL'也被计算在内。 –