我正在使用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;
它给了我正确的输出,但问题是如何在我的查询中使用这种双重性来阻止?
答案 0 :(得分: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 :(得分:2)
这样做的方法很多。
<强> 1。 Common Table Expression - 在SQL Server 2005中引入
;用cte as(
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;
其他方法是使用临时表,您必须首先插入数据并在列上执行进一步操作的视图,但我不认为它们是您的问题所必需的。
注意:
如果需要,CTE和派生表只能使用一次 对您的数据执行多个操作,然后使用临时 表
性能方面,CTE和派生表具有相似的性能, 它只是一个偏好问题,你想要哪个更具可读性