如下所示如何在SQL Server中绑定数据

时间:2019-02-10 11:49:27

标签: sql-server-2008

with cteRecurs(AncestorId, Id, Node, ParentId) as  
(  
    Select 
        InvoiceID, InvoiceID, C_Name, InvoiceLevel  
    from 
        Invoice  
    union all  
    Select  
        cteRecurs.AncestorId, Invoice.InvoiceID, Invoice.C_Name, Invoice.InvoiceLevel  
    from 
        cteRecurs,  
        Invoice  
    where 
        Invoice.InvoiceLevel = cteRecurs.Id  
)  
--  select * from cteRecurs where AncestorId='IN1'
select 
    AncestorId, count(*) - 1 BillCount 
into 
    #temp 
from 
    cteRecurs 
group by 
    AncestorId  


select 
    a.AncestorId, b.C_ID, b.C_Name, a.BillCount,
    isnull(c.Income, 0) Income,  
    isnull(d.BillCount, 0) Closedbill,
    isnull(d.Income, 0) ClosedIncome,  
    (a.BillCount - isnull(d.BillCount, 0)) NewBillCount,
    (isnull(c.Income, 0) - isnull(d.Income, 0)) NewIncome   
from 
    #temp a  
inner join  
    Invoice b on a.AncestorId = b.InvoiceID   
left join 
    tbl_BinaryIncome c on a.BillCount between c.BillCountfrom and c.BillCountTo   
left outer join 
    hisBinIncome d on a.AncestorId = d.AncestorID  
where 
    a.BillCount > 0  
order by 
    a.BillCount desc, Income desc 

--select * from #temp  where BillCount>0
--select sum(BillCountfrom),sum(Income) from tbl_BinaryIncome where BillCountfrom<='81'


drop table #temp

此查询select * from tbl_BinaryIncome返回的数据为:

AncestorId  C_ID   C_Name         BillCount Income  Closedbill  ClosedIncome NewBillCount NewIncome
IN1         Admin  TOSHAN RAJPUT  81        500.00  0           0.00         81           500.00

但我希望此数据为:

AncestorId  C_ID    C_Name          BillCount   Income  Closedbill  ClosedIncome NewBillCount NewIncome
IN1         Admin   TOSHAN RAJPUT    3           50.00  0           0.00          3            50.00
IN1         Admin   TOSHAN RAJPUT    9          100.00  0           0.00          9           100.00
IN1         Admin   TOSHAN RAJPUT   27          200.00  0           0.00         27           200.00

代表表数据为:

ID  BillCountfrom BillCountTo Income
1   3                 8          50.00
2   9                26         100.00
3   27               80         200.00
4   81              242         500.00
5   243             728        1000.00
6   729            2186        2000.00
7   2187           6560        5000.00
8   6561          10000       10000.00

0 个答案:

没有答案