返回列数的条件

时间:2015-09-09 06:47:11

标签: sql sql-server

我在下面有friends表。

-----------------------------
| id | user_id | friends_id |
-----------------------------
| 1  |    1    |     2      |
-----------------------------
| 2  |    1    |     3      |
-----------------------------
| 3  |    1    |     4      |
-----------------------------
| 4  |    2    |     1      |
-----------------------------
| 5  |    3    |     5      |
-----------------------------
| 6  |    4    |     5      |
-----------------------------

SQL查询:

select user_id, friends_id from friends where user_id = 1

以上查询给出了以下结果。

------------------------
| user_id | friends_id |
------------------------
|    1    |     2      |
------------------------
|    1    |     3      |
------------------------
|    1    |     4      |
------------------------

我想得到这样的结果:

------------------------
| user_id | friends_id |
------------------------
|    1    |   many     |
------------------------
  • 如果任何用户有超过1的朋友,我必须写'很多'字。
  • 如果有任何用户有1位朋友,我必须写下他的身份证。

我怎么能这样做? 我google了,无法解释谷歌我的问题。

4 个答案:

答案 0 :(得分:1)

执行GROUP BY来统计朋友数量。使用CASE返回'许多'如果超过1个朋友,或者friend_id(如果只有一个)(需要CAST到字符类型,与'许多'兼容。)

select user_id, 
       case when count(friends_id) > 1 then 'Many'
       else cast(min(friends_id) as varchar(11)) end as friends_id
from friends
group by user_id

答案 1 :(得分:0)

我更新了查询并包含

SQL FIDDLE DEMO

WITH fCount as (
      SELECT user_id, min(friends_id) friends_id, count(friends_id) nFriend
      FROM friends
      GROUP BY user_id
)
select user_id, CASE 
                    WHEN nFriend > 1 THEN 'many'
                    ELSE cast(friends_id as nvarchar(10))
                END friends_id 
from fCount 

答案 2 :(得分:0)

试试这个

select user_id, CASE 
                    WHEN count(friends_id) > 1 THEN 'many'
                    ELSE friends_id
                END friends_id 
from friends 
where user_id = 1

答案 3 :(得分:0)

您好,您可以使用以下查询:

                CREATE TABLE #Temp (
                ID INT Identity(1, 1)
                ,UID INT
                ,f_id NVARCHAR(10)
                )

            INSERT INTO #temp
            SELECT 1
                ,2

            UNION ALL

            SELECT 1
                ,3

            UNION ALL

            SELECT 1
                ,4

            UNION ALL

            SELECT 2
                ,1

            SELECT uid
                ,COUNT(f_id) AS COUNT_of_Friends
            INTO #Temp2
            FROM #temp
            GROUP BY Uid

            SELECT t1.Uid
                ,CASE 
                    WHEN t2.COUNT_of_Friends > 1
                        THEN 'Many'
                    ELSE f_id
                    END AS F_id
            FROM #temp T1
            INNER JOIN #Temp2 T2 ON T1.Uid = t2.Uid