码迷,mamicode.com
首页 > 其他好文 > 详细

在GROUP BY中的做文章(一道题五中简答方法!)

时间:2015-12-16 22:59:17      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

被废话,直接上代码

测试代码,数据如下:

CREATE TABLE #T(
 TIMES VARCHAR(15),
 RESULT NVARCHAR(20) 
)

INSERT  INTO #T 
SELECT  2005-05-09,
UNION ALL
SELECT 2005-05-09, 
UNION ALL
SELECT 2005-05-09, 
UNION ALL
SELECT 2005-05-09, 
UNION ALL
SELECT 2005-05-10, 
UNION ALL
SELECT 2005-05-10, 
UNION ALL
SELECT 2005-05-10, 

 

要求结果:

       时间          胜  负
2005-05-09      2  2
2005-05-10      1  2

 方法一:CASE 的妙用

--结果
--CASE 里面做文章滴呀;
--我艹尼玛;
--CASE 用户group by 之后的逻辑判断滴呀;--好逻辑,尼玛case的妙用滴呀;

SELECT TIMES,
 SUM(CASE WHEN RESULT= THEN 1 ELSE 0 END) AS 胜,
 SUM(CASE WHEN RESULT= THEN 1 ELSE 0 END) ASFROM #T
GROUP BY TIMES

 方法二:共用表达式+COUNT()

GO
WITH A AS(
SELECT TIMES,COUNT(*) AS WIN FROM #T
WHERE RESULT=
GROUP BY TIMES
), B AS(
SELECT TIMES,COUNT(*) AS LOSE FROM #T
WHERE RESULT=
GROUP BY TIMES)

SELECT AA.TIMES,AA.WIN,BB.LOSE FROM A AA INNER JOIN B BB
ON AA.TIMES=BB.TIMES

 方法三:既然能够使用我们的共用表达式,那么自然能使用我们的临时表滴啦

 

 方法四:

  

  SELECT A.TIMES,A.WIN,B.LOSE FROM 
  (
   SELECT TIMES,COUNT(*) WIN FROM #T
   WHERE RESULT=
   GROUP BY TIMES
  ) AS A,
  
  (
   SELECT TIMES,COUNT(*) LOSE FROM #T
   WHERE RESULT=
   GROUP BY TIMES
  
  ) AS B
  
  WHERE A.TIMES=B.TIMES

 方法五:

   

 SELECT N.TIMES,N.WIN,M.LOSE FROM (
  (
    SELECT TIMES,COUNT(*) AS WIN FROM #T
    WHERE RESULT=
    GROUP BY TIMES)N 
    INNER JOIN 
    (SELECT TIMES ,COUNT(*) AS LOSE FROM #T
    WHERE RESULT=
    GROUP BY TIMES
    )M ON N.TIMES=M.TIMES
  
  )
  
  --中间的赛选条件也可以这样写滴呀
  --我艹尼玛
  SELECT TIMES,COUNT(*) as win  FROM #T
  GROUP BY TIMES,RESULT
  HAVING RESULT=

 

  帅~

在GROUP BY中的做文章(一道题五中简答方法!)

标签:

原文地址:http://www.cnblogs.com/mc67/p/5052448.html

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