在没有表或cte的情况下进行内联语句

时间:2013-09-18 16:04:58

标签: sql sql-server tsql

我需要在不使用#Temp表或表变量的情况下执行以下操作。不能用GROUP BY做CTE。有没有办法做到这一点?

select Title, count(*) as PlayCount
into #Temp
from LC l 
join Play p on p.lcID = l.lcID
group by Title

declare @Max int 
select @Max = max(PlayCount) from #Temp

select Title, PlayCount, cast(PlayCount as float) / cast(@Max as float) as Weight
from #Temp

3 个答案:

答案 0 :(得分:3)

使用子查询/ cte和MAX() OVER()

SELECT Title, PlayCount, PlayCount*1.0 / Max_CT AS WEIGHT
FROM (SELECT Title
           , COUNT(*) AS PlayCount
           , MAX(COUNT(*)) OVER() AS Max_CT
      FROM LC l 
      JOIN PLAY P ON P.LCID = L.LCID
      GROUP BY Title
     )sub

(假设MS SQL 2005或更新版本)

答案 1 :(得分:1)

子查询?也许不是最干净的

select Title, count(*) as PlayCount , count(*) / tot
from LC l join Play p on p.lcID = l.lcID ,
(select max(a) as tot from (select count(*)  as a from LC group by lcid))
group by Title , tot

不完全确定哪个表正在做什么,但上面应该给你一个想法

答案 2 :(得分:0)

select Title, count(*) as PlayCount, cast(count(*) as float) / cast(
(
select max(PlayCount) from (select count(*) as PlayCount
from LC l 
join Play p on p.lcID = l.lcID
group by Title
) q) as float) as Weight
from LC l
join Play p on p.lcID = l.lcID
group by title

我认为这至少是接近的。但是“没有CTE”的要求似乎是人为的 - 这是大学还是s.t的实验室测试?