我正在使用sql server 2008,其中我有一些麻烦我找不到一列
TblMaster
ID Name City
1 Hiren Juanagadh
2 Ashish Gandhinagar
2 Mayur Ahmedabad
3 Hitesh Junagadh
4 Nipun Ahmedabad
4 Vivek Rajkot
4 Samir Surat
5 Sagar Vadodara
现在我想要Anoter列CountId所以我想要输出如下
TblMaster
ID Name City CountId
1 Hiren Juanagadh 0
2 Ashish Gandhinagar 2
2 Mayur Ahmedabad 2
3 Hitesh Junagadh 0
4 Nipun Ahmedabad 3
4 Vivek Rajkot 3
4 Samir Surat 3
5 Sagar Vadodara 0
表示如果Id列只有一个,则CountId = 0 如果Id列多于一个,则CountId = Idcolumn的计数
答案 0 :(得分:1)
尝试此查询:::
select *,(case when (select count(id) from TblMaster )=1
then 0 else (select count(id) from TblMaster) end) as count
from tblmaster
答案 1 :(得分:1)
准备表
declare @T table (
id int,
Name nvarchar(6),
City nvarchar(20))
insert @T values
( 1 , 'Hiren', 'Juanagadh'),
( 2 , 'Ashish', 'Gandhinagar'),
( 2 , 'Mayur', 'Ahmedabad'),
( 3 , 'Hitesh', 'Junagadh'),
( 4 , 'Nipun', 'Ahmedabad'),
( 4 , 'Vivek', 'Rajkot'),
( 4 , 'Samir', 'Surat'),
( 5 , 'Sagar', 'Vadodara')
选择陈述
没有1-> 0校正
SELECT *, CountID = count(*) over (Partition by ID)
from @T
使用1-> 0校正
select id, Name,City,CountID = case when CountID = 1 then 0 else CountID end
from (
SELECT *, CountID = count(*) over (Partition by ID)
from @T )
RES