0

我正在使用 SQL Server 2005。我Count()在查询中使用了 3 次

select    
    p.side,
    p.uid as uid,
    count (p.side) as cside,
    (count (p.side)/ 3) as pairs,
    ((count (p.side)/ 3) * 15 ) as commisonPrice
from  
    tempComm as p
group by 
    p.side , p.uid
order by 
    p.uid;

它给了我正确的输出,但问题是如何通过在查询中使用这种重复性来防止?

4

2 回答 2

2
select 
    side,
    uid,
    cside,
    cside/3 as pairs,
    cside/3*15 as commisonPrice 
from
(
    select
    p.side ,
    p.uid as uid , 
    count (p.side) as cside
    from tempComm as p 
    group by p.side , p.uid
) t
order by uid; 
于 2013-10-12T08:35:45.857 回答
2

有几种方法可以做到这一点。

1.公用表表达式- SQL Server 2005 中引入

; 与 cte 为 (

    select    
          p.side,
          p.uid as uid,
          count (p.side) as cside
    from  tempComm as p
    group by p.side , p.uid

)

select * , cside / 3 as pairs , (cside / 3) * 15 as commisonPrice
from cte
order by p.uid;

2. 派生表

select 
    side,
    uid,
    cside,
    cside/3 as pairs,
    (cside/3)*15 as commisonPrice 
from
(
    select
    p.side ,
    p.uid as uid , 
    count (p.side) as cside
    from tempComm as p 
    group by p.side , p.uid
) t
order by uid; 

其他方法是使用临时表,您必须首先在其中插入数据并对列执行进一步操作的视图,但我认为您的问题不需要它们。

笔记 :

  1. CTE 和派生表都只能使用一次,如果您需要对数据执行多次操作,请使用临时表。

  2. 性能方面,CTE 和派生表具有相似的性能,只是您希望哪一个更具可读性和可理解性的偏好问题。

于 2013-10-12T08:51:20.310 回答