机床id 机床型号 机床编号 机床状态
id jcxh jcbh jczt
一个机床型号里面包括很多机床编号,机床型号+机床编号=唯一确定一个机床
select count(jcbh),jcxh from JCXINXI group by jcxh这个语句只能做到按照机床型号统计,每个型号有多少机床,可是不能统计每个型号中机床状态为0的多少个,1的多少个,2的多少个。
一个语句可以统计出来的
就是结果列为: jcxh count(jcbh) count(状态为0) count(状态为1) count(状态为2)
解答:用case 吧,语句自己写:count(状态为0):sum(case jczt when 0 then 1 else 0 end )
declare
@s varchar(8000)
set @s='select jcxh,count(jcbh) as jcbh'
select @s=@s+',[状态为'+jczt+']=sum(case jczt when '''+jczt+''' then 1 else 0 end)'
from tablename group by jczt
exec(@s+'from tablename group by jcxh')
如果我用一个列除以另一个列生成一个新的列怎么办啊num1/num2 这样好像不行
select jcxh,count(jcbh)as num,
sum(case jczt when 0 then 1 else 0 end )as zt0,
sum(case jczt when 1 then 1 else 0 end )as zt1,
sum(case jczt when 2 then 1 else 0 end )as zt2,
zt0*1.0/num from JCXINXI group by jcxh提示说我zt0,num无效。不加zt0*1.0/num,就可以运行成功。但是我想计算那个百分比就不行了。
declare
@sql varchar(8000)
set @sql='select jcxh,count(jcbh) '
select @sql=@sql+',['+jczt+']=
sum(case jczt when '''+jczt+''' then 1 else 0 end)'
from tab group by jczt
exec(@sql+' from tab group by jcxh')
jcxh count(jcbh) jczt1 jczt2a321b431
改為Select *,zt0*1.0/num From(select jcxh,count(jcbh)as num,sum(case jczt when 0 then 1 else 0 end )as zt0,sum(case jczt when 1 then 1 else 0 end )as zt1,sum(case jczt when 2 then 1 else 0 end )as zt2from JCXINXI group by jcxh) A計算列不能直接拿來用的
保留2位小數Select *,Cast(zt0*1.0/num As Numeric(10,2)) From(select jcxh,count(jcbh)as num,sum(case jczt when 0 then 1 else 0 end )as zt0,sum(case jczt when 1 then 1 else 0 end )as zt1,sum(case jczt when 2 then 1 else 0 end )as zt2from JCXINXI group by jcxh) AA是查詢出來的這個紀錄集的別名select jcxh,count(jcbh)as num,sum(case jczt when 0 then 1 else 0 end )as zt0,sum(case jczt when 1 then 1 else 0 end )as zt1,sum(case jczt when 2 then 1 else 0 end )as zt2from JCXINXI group by jcxh