想要变成下面的格式
代码:
select e.CONTENT,A0101,A0190,A0177,A0185,d.Degree as '迟到',b.cut,b.Degree,c.Degree as '实际打卡次数' from A01 a left join (select EmployeeID,b.Type as cut,COUNT(*) as Degree
from AP_INCIDENT a,AP_INCIDENTCLASS b
where a.ClassID=b.GUID
group by EmployeeID,b.Type)
b on a.A0188=b.EmployeeID left join (select count(GUID) as Degree,EmployeeID from AP_ATTRECORD group by EmployeeID) c on a.A0188=c.EmployeeID
left join (select count(GUID) as Degree,EmployeeID from AP_ATTRECORD where IsLate=1 group by EmployeeID) as d on a.A0188=d.EmployeeID
join (select content,DEPT_ID from DEPTCODE) as e on e.DEPT_ID=a.DEPT_ID
order by b.Degree desc
各位大神 怎么弄啊
行列转换
可以用select代替exec看到具体数据库具体执行了什么语句
思路有点特别是值与值进行比对,不是变量对值
declare
@sql as varchar(1000),@sql1 as varchar(1000),
@i_Process as NVARCHAR(20),
@i_WD_CD as NVARCHAR(20),
@i_EMP_NM as NVARCHAR(20)
begin
select @sql=ISNULL(@sql+'],[','')+WD_ITEM_CD FROM TB_WD_QA_ITEM GROUP BY WD_ITEM_CD;
select @sql1=ISNULL(@sql1+'","','')+WD_ITEM_CD FROM TB_WD_QA_ITEM GROUP BY WD_ITEM_CD;
set @sql1='"'+@sql1+'"'
select @sql1
set @sql='['+@sql+']';
SET @i_Process ='ALL';
SET @i_WD_CD='';
SET @i_EMP_NM='刘';
select @sql
exec ('select * from (
select A.WD_ST_CD,D.EMP_NM,A.WD_CD,A.Prosition,A.Thickness,A.FNO,A.PNO,A.RANGE,B.WD_CRT_RANG,B.WD_ITEM_CD,A.WPQR_NO,CONVERT(varchar(10),A.CERT_DATE,120) CERT_DATE,
E.CODE_CNAME
from TB_WD_APLLY A,TB_WD_RESULT B,TB_WD_QA_ITEM C,TB_EMP D,TB_CODE_MST E
WHERE A.WD_ST_CD=B.WD_ST_CD AND A.CRT_NO=B.CRT_NO AND A.EMP_CD=B.EMP_CD
AND B.WD_ST_CD=C.WD_ST_CD AND B.WD_ITEM_CD=C.WD_ITEM_CD
AND A.EMP_CD=D.EMP_CD and E.CODE_NO=A.CERT_GBN AND
E.AFF_DVN=''QM'' AND E.CODE_DVN=''008'' AND E.CODE_NO<>''001''
AND A.WD_ST_CD =CASE '''+@i_Process+''' when ''ALL'' THEN A.WD_ST_CD
ELSE '''+@i_Process +'''
END
AND B.WD_CD = CASE '''+@i_WD_CD +''' WHEN NULL THEN B.WD_CD
WHEN '''' THEN B.WD_CD
ELSE '''+@i_WD_CD+'''
END
AND D.EMP_NM LIKE CASE WHEN '''+@i_EMP_NM+''' = NULL THEN D.EMP_NM
WHEN '''+@i_EMP_NM+''' = '''' THEN D.EMP_NM
ELSE ''%'''+ '+''' + '' + @i_EMP_NM+ '''+'+'' +'''%''
END) p
PIVOT(
MAX(WD_CRT_RANG)
FOR WD_ITEM_CD IN ('+@sql+')
) as Q')
end
可以参考下这个代码
行列转换?能说详细点么?
这是一个复杂的转换,相信你也认同这一点。
这个 SQL 即使写出来也是相当复杂,且不利于维护的。
如果是我,我会分至少成两步去做:
1.从数据库查询原始数据, select a, b, c from table;
2.在你程序中进行统计, (比如用c#)比在 Sql 中处理简单多了;
复杂的话是不是先写成视图?然后对视图行列转换?
你去百度找一下行转列,不要太多。
如果楼主用的是sql server 2005及以上版本可以直接使用Pivot或者UnPivot来进行行专列的转换。当然也可能需要动态语句来做。
如果是2000的话就只能自己写了。要是需要转化的列很多那就要用动态语句来做了。如果就只有固定的几列可以直接写。
楼主可以把表结构贴上来,大家可以帮你详细写一下。