0

我需要在不使用 #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
4

3 回答 3

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 或更新版本)

于 2013-09-18T16:13:48.953 回答
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

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

于 2013-09-18T16:10:16.747 回答
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”的要求似乎是人为的——这是大学的实验室测试还是 st?

于 2013-09-18T16:16:02.007 回答