码迷,mamicode.com
首页 > 数据库 > 详细

一句SQL按照某个字段数值拆分出对应的数据条数,借助数据库常量表【master..spt_values】实现

时间:2016-07-31 11:37:28      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

简介:master..spt_values,数据行拆分简单小技巧 

SELECT  ProjGUID ,
        CostGUID ,
        SUM(FtAmount) AS FtAmount ,
        BeginMonth ,
        EndMonth ,
        ( EndMonth - BeginMonth ) + 1 AS RowCountNum
FROM    cb_Loan2Cost
WHERE   LoanGUID = 6D88EB2B-18FA-4A4A-9ADB-9873B0F14381
GROUP BY ProjGUID ,
        CostGUID ,
        EndMonth ,
        BeginMonth

SQl结果集查出如下图:

技术分享

一句话拆分出对应的数据条数:

SELECT  
M.ProjGUID,
M.CostGUID,
CASE WHEN

 M.XnMonth=M.EndMonth

THEN M.NewFtAmount+(M.FtAmount-M.NewFtAmount*M.FactMonth) 

ELSE M.NewFtAmount END FactFtAmount,
M.FactMonth 
FROM (               
SELECT  T.ProjGUID ,
        T.CostGUID ,
        T.FtAmount / T.RowCountNum AS NewFtAmount ,
        T.FtAmount,
        T.BeginMonth ,
        T.EndMonth ,
        CASE WHEN BeginMonth = EndMonth THEN EndMonth ELSE spt.number END FactMonth,
        spt.number AS XnMonth
FROM    ( SELECT    ProjGUID ,
                    CostGUID ,
                    SUM(FtAmount) AS FtAmount ,
                    BeginMonth ,
                    EndMonth ,
                    ( EndMonth - BeginMonth ) + 1 AS RowCountNum
          FROM      cb_Loan2Cost
          WHERE     LoanGUID = 6D88EB2B-18FA-4A4A-9ADB-9873B0F14381
          GROUP BY  ProjGUID ,
                    CostGUID ,
                    EndMonth ,
                    BeginMonth
        ) T ,
        master..spt_values spt
WHERE   T.RowCountNum >= spt.number
        AND spt.type = P
        AND spt.number > 0
 )M

最终结果集如下图:

技术分享

 

拆分SQL核心如下

借助数据库常量表:master..spt_values

此表记录都是数据库中常用的常量值

SELECT number FROM master..spt_values 

简单的小例子

create table T(A varchar(10), B varchar(10),  C int)

 

insert into T
select AA,            ,                 5 union all
select AB,            ,                 3

技术分享

select t.A 编码, t.B as 名称,1 as 数量 
from t,master..spt_values s
where t.c>= s.number and s.type= P and s.number >0

技术分享

一句SQL按照某个字段数值拆分出对应的数据条数,借助数据库常量表【master..spt_values】实现

标签:

原文地址:http://www.cnblogs.com/KingUp/p/5722583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!