zoukankan      html  css  js  c++  java
  • SQL Server中Pivot()函数实现动态行转列

    一般情况下Pivot()函数中in中只能写死,因为PIVOT()的in中不支持子查询,所以这样的话只能用存储过程来解决;

    CREATE PROCEDURE InsurancePivot  

    @Foldercode VARCHAR(50),  

    @isY VARCHAR(4)

    AS

    BEGIN     DECLARE @ColumnNames VARCHAR(3000)     

    SET @ColumnNames=''      

    SELECT        @ColumnNames = @ColumnNames + '[' + TESTNO + '],'    

    FROM        (        SELECT TESTNO FROM ORDTASK            

    LEFT JOIN TESTS ON TESTS.TESTCODE = ORDTASK.TESTCODE            

    WHERE ORDTASK.FOLDERNO IN (SELECT FOLDERNO FROM FOLDERS WHERE FOLDERCODE = @Foldercode)        ) t      

    SET @ColumnNames= LEFT(@ColumnNames, LEN(@ColumnNames)-1)      

    DECLARE @selectSQL NVARCHAR(3000)      

    SET @selectSQL=  'SELECT P.* FROM ( select  foldercode as "受理单编号",ordcode as "样品编号",orders.ORIGINALNO as "原始编号", orders.name  as "姓名", pa.SEX as "性别",                         pa.AGE as "年龄", pa.ADDRESS as "现住址", folders.DATERECV as "收样日期",FINAL,name.TESTCODE,                         orders.SAMPLINGDATE, TESTNO   

    from orders   left join folders on orders.folderno = folders.folderno   

    left join PATIENTS pa on pa.PID = orders.PID   

    left join (select ordno, results.FINAL,tests.testno ,tests.testcode                        

    from analytes                        

    left join ORDTASK on ordtask.TESTCODE = analytes.TESTCODE and ordtask.METHOD = analytes.METHOD                        

    left join results on results.ANALYTE = analytes.ANALYTE and results.ORDTASKNO = ordtask.ORDTASKNO                        

    left join tests on tests.testcode = analytes.TESTCODE                        

    where analytes.displayflag = '''+@isY+''') name on name.ordno = orders.ordno   where foldercode = '''+@Foldercode+''' ) a   

    pivot( max(FINAL) for TESTNO in ({0}))p'      

    SET @selectSQL= REPLACE(@selectSQL,'{0}',@ColumnNames)   

    EXEC sp_executesql @selectSQL

    END

    GO

  • 相关阅读:
    上传预览图片
    css3图片3D翻转效果
    获取新浪天气api显示天气情况(转)
    matlab添加M_map工具箱(转 http://blog.sina.com.cn/s/blog_491b86bf0100srt9.html)
    Matlab read_grib.r4 安装新方法(转自:http://blog.sina.com.cn/s/blog_9f36648b010179s7.html)
    grb文件的读取
    Windows 7 防火墙对Virtualbox guest的影响
    Virtualbox修改bios信息安装Windows XP OEM
    Wordpress编辑器(Tinymce)在Chrome中动态修改图片大小
    Android流行的框架整理
  • 原文地址:https://www.cnblogs.com/zy20160117/p/7428507.html
Copyright © 2011-2022 走看看