当前位置: 代码迷 >> Sql Server >> 来了3个口试的,居然有2人做错这道题.
  详细解决方案

来了3个口试的,居然有2人做错这道题.

热度:4   发布时间:2016-04-24 10:54:57.0
来了3个面试的,居然有2人做错这道题...

?  有如下表:
日期(rstime) 结果(result)
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负

如果要生成下列结果,该如何写sql语句?
日期 胜 负
2005-05-09 2 2
2005-05-10 1 2



都是出来工作2-3年的。。。
------解决方案--------------------
如果只是纸面作答,十有八九会错,因为语法比较复杂不容易记,如果是上机就没有这个问题了。
------解决方案--------------------

SELECT RSTIME AS 日期,
MAX(CASE RESULT WHEN '勝' THEN TOTAL ELSE '' END) AS 勝,
MAX(CASE RESULT WHEN '負' THEN TOTAL ELSE '' END) AS 負
FROM  
(
SELECT RSTIME,RESULT,COUNT(RESULT) AS TOTAL
FROM DBO.THETABLE
GROUP BY RSTIME,RESULT
) A
GROUP BY RSTIME

有分么?
------解决方案--------------------
简单的行转列;

create table tt(rstime datetime,result varchar(10))

insert into tt
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',    '负' 
go


select rstime,
       count(case when result='胜' then 1 else null end) 胜,
       count(case when result='负' then 1 else null end) 负     
 from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/

------解决方案--------------------
这样也可以:


select rstime,
       sum(case when result='胜' then 1 else 0 end) 胜,
       sum(case when result='负' then 1 else 0 end) 负     
 from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/

------解决方案--------------------
引用:
这样也可以:


select rstime,
       sum(case when result='胜' then 1 else 0 end) 胜,
       sum(case when result='负' then 1 else 0 end) 负     
 from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/


------解决方案--------------------
引用:
这样也可以:


select rstime,
       sum(case when result='胜' then 1 else 0 end) 胜,
       sum(case when result='负' then 1 else 0 end) 负     
 from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/


學習了
------解决方案--------------------
case when then ...
------解决方案--------------------
出来工作两三年还得看平时用得到不...
当然关键还得看个人
------解决方案--------------------
 或许不奇怪吧,这个世道太过流行GOOGLE+BAIDU COPY AND PASTE
------解决方案--------------------
引用:
这样也可以:


select rstime,
       sum(case when result='胜' then 1 else 0 end) 胜,
       sum(case when result='负' then 1 else 0 end) 负     
 from tt
group by rstime
/*
rstime 胜 负
2005-05-09 00:00:00.000 2 2
2005-05-10 00:00:00.000 1 2
*/



------解决方案--------------------
引用:
这样也可以:


select rstime,
       sum(case when result='胜' then 1 else 0 end) 胜,
       sum(case when result='负' then 1 else 0 end) 负     
 from tt
group by rstime
/*
  相关解决方案