1

当 COUNT() < 2 但由于某种原因我的语法不正确时,我试图从“years”一词中删除“s”:

错误: 关键字“IF”附近的语法不正确。关键字“convert”附近的语法不正确。

stuff(
        (
        select ',' + Related_name + ' (' + (select
        IF COUNT(begin_date) > 1 BEGIN convert(varchar(10), COUNT(begin_date))  + ' years)' END
        ELSE BEGIN convert(varchar(10), COUNT(begin_date))  + ' year)'
        from cus_relationship subInnerR
        where subInnerR.master_customer_id = c.master_customer_id
        and subInnerR.related_master_customer_id = innerR.related_master_customer_id
        and subInnerR.relationship_type = 'ADVSPR'
        and subInnerR.relationship_code = 'CLUB'
        and subInnerR.reciprocal_code = 'FACADV')
        from cus_relationship innerR
        where [...]
4

4 回答 4

2

像这样尝试(正如 gvee 在评论中所评论的那样,这减少了一些重复的代码!!):-

 select ',' + Related_name + ' (' + (select
    Convert(varchar(10), Count(begin_date)) + ' year' + 
    CASE WHEN Count(begin_date) > 1 THEN 's'    ELSE '' END + ')'
    from cus_relationship subInnerR
    where subInnerR.master_customer_id = c.master_customer_id
    and subInnerR.related_master_customer_id = innerR.related_master_customer_id
    and subInnerR.relationship_type = 'ADVSPR'
    and subInnerR.relationship_code = 'CLUB'
    and subInnerR.reciprocal_code = 'FACADV')
    from cus_relationship innerR
    where [...]
于 2013-09-18T14:47:16.223 回答
1

也许这有帮助

在 tsql 你使用CASE而不是IF

于 2013-09-18T14:47:49.863 回答
1

我不喜欢重用相同的代码,所以我会这样使用CASE

CONVERT(VARCHAR(10), COUNT(begin_date)) 
+ ' year' 
+ CASE WHEN COUNT(begin_date) > 1 THEN 's' ELSE '' END
+ ')'

拆分为多行以提高可读性

于 2013-09-18T14:51:13.340 回答
0

您需要使用CASE语句而不是IF

case
    when COUNT(begin_date) > 1 then
        convert(varchar(10), COUNT(begin_date))  + ' years)'
    else
        convert(varchar(10), COUNT(begin_date))  + ' year)'
end
于 2013-09-18T14:46:19.750 回答