案件陈述,以确定我是否应该结合

时间:2015-05-19 13:21:18

标签: sql sql-server sql-server-2012 case union

我目前想要做某种条件联合。给出以下示例:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

如果'用户'的数量是> = 2,我想只想结合第二个陈述,否则不要将两者合并。

总之,如果表只有2个或更多值,我想附加一个表格。

4 个答案:

答案 0 :(得分:10)

你可以使用一个丑陋的黑客这样的东西,但我认为Tim's answer更好:

SELECT  age, name
FROM    users
UNION ALL

SELECT 25 AS age, 'Betty' AS name
WHERE (SELECT COUNT(*) FROM users) > 1

答案 1 :(得分:7)

如果它在存储过程中,您可以使用If...Else

IF (SELECT COUNT(*) FROM users) < 2
 BEGIN
  SELECT  age, name
  FROM    users
  END
ELSE
  SELECT  age, name
  FROM    users
  UNION ALL
  SELECT  25 AS age, 'Betty' AS name

否则你可以尝试这样的事情:

SELECT  age, name
  FROM    users
  UNION ALL
  SELECT  TOP 1 25 AS age, 'Betty' AS name
  FROM users
  WHERE (SELECT COUNT(*) FROM users) >= 2

请注意,我已使用UNION ALL,因为您似乎不想删除重复项。

在这里玩:http://sqlfiddle.com/#!6/a7540/2323/0

修改:我更喜欢Zohar's而不是我的第二种方法。因此,如果您可以使用If....Else,则不要使用WHERE (SELECT COUNT(*) FROM users) > 1而不使用表格。

答案 2 :(得分:5)

以下内容应该有效:

SELECT  age, name
FROM    users

UNION ALL

SELECT age, name
FROM (SELECT  25 AS age, 'Betty' AS name) x
CROSS APPLY (SELECT COUNT(*) FROM users) y(cnt)
WHERE y.cnt >= 2

如果UNION ALL表的记录少于2条,NULL的第二部分将为users

答案 3 :(得分:1)

SELECT age
     , name
FROM   users

UNION

SELECT 25 As age
     , 'Betty' As name
WHERE  EXISTS (
         SELECT Count(*)
         FROM   users
         HAVING Count(*) >= 2
       )
;