2 qq 31071631 qq_31071631 于 2016.02.17 09:20 提问

那在sql server中该怎么写才能达到mysql中的分组效果呢,分出的结果不一样

SELECT CASE WHEN AGE <= 10 THEN '1' WHEN AGE > 10 AND AGE <= 20 THEN '2' WHEN AGE > 20 AND AGE <= 30 THEN '3' WHEN AGE > 30 AND AGE <= 40 THEN '4' WHEN AGE > 40 AND AGE <= 50 THEN '5' WHEN AGE > 50 AND AGE <= 60 THEN '6' WHEN AGE > 60 AND AGE <= 70 THEN '7' WHEN AGE > 70 AND AGE <= 80 THEN '8' WHEN AGE > 80 AND AGE <= 90 THEN '9' WHEN AGE > 90 AND AGE <= 100 THEN 'a' WHEN AGE > 100 THEN 'b' END allshuju ,COUNT(*) renshu,OUT_MAIN_DIAG_RST leibie FROM WORK_BASY_DATA where 1=1 and OUT_DT >= '2012-10-1' and OUT_DT <= '2012-10-31' GROUP BY allshuju,OUT_MAIN_DIAG_RST having OUT_MAIN_DIAG_RST!='' AND allshuju!=''

4个回答

bdmh
bdmh   Ds   Rxr 2016.02.17 09:23

sqlserver 中也有 case when 一样的

qq_31071631
qq_31071631 效果不一样
接近 2 年之前 回复
qq_31071631
qq_31071631 效果不一样
接近 2 年之前 回复
qq_31071631
qq_31071631 效果不一样
接近 2 年之前 回复
enpterexpress
enpterexpress   2016.02.17 09:29

一样

qq_31071631
qq_31071631 分组效果不一样
接近 2 年之前 回复
qq_25093755
qq_25093755   2016.02.17 10:36

mysql和sql server差别不大

qq_31071631
qq_31071631 分出的结果不一样
接近 2 年之前 回复
ch21st
ch21st   2016.02.17 11:17

SQL Server也支持CASE WHEN,但你的写法在SQL Server会有问题,你的语句中allshuju不是实际的字段,而是一个别名,不能再GROUP BY中直接用
要不你把GROUP BY和HAVING后的allshuju换成上面的CASE WHEN完整判断,要不就在嵌套一层

 SELECT t.allshuju,t.OUT_MAIN_DIAG_RST ,COUNT(*) renshu FROM (
    SELECT 
    CASE 
    WHEN AGE <= 10 THEN '1' 
    WHEN AGE > 10 AND AGE <= 20 THEN '2' 
    WHEN AGE > 20 AND AGE <= 30 THEN '3' 
    WHEN AGE > 30 AND AGE <= 40 THEN '4' 
    WHEN AGE > 40 AND AGE <= 50 THEN '5' 
    WHEN AGE > 50 AND AGE <= 60 THEN '6' 
    WHEN AGE > 60 AND AGE <= 70 THEN '7' 
    WHEN AGE > 70 AND AGE <= 80 THEN '8' 
    WHEN AGE > 80 AND AGE <= 90 THEN '9' 
    WHEN AGE > 90 AND AGE <= 100 THEN 'a' 
    WHEN AGE > 100 THEN 'b' END allshuju 
    ,OUT_MAIN_DIAG_RST leibie 
    FROM WORK_BASY_DATA 
    where 1=1 and OUT_DT >= '2012-10-1' and OUT_DT <= '2012-10-31' 
) t 
GROUP BY t.allshuju,t.OUT_MAIN_DIAG_RST 
having t.OUT_MAIN_DIAG_RST!='' AND t.allshuju!=''
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!