如何使用COUNT值在SQL中编写条件

时间:2009-05-18 11:15:50

标签: sql-server

我有两个表,我需要根据计数

将值插入临时表
IF(@COUNT>1)
BEGIN
insert into #temp_cols  
SELECT M.ID_PK,  
substring(M.NAME,1,1)+'_'+ N.NAME 
FROM TEST_TABLE1 M WITH (NOLOCK) 
LEFT JOIN TEST_TABLE2 N  ON M.ID_PK=N.ID_FK  
END

ELSE
BEGIN
insert into #temp_cols  
SELECT M.ID_PK,  
N.NAME 
FROM TEST_TABLE1 M WITH (NOLOCK) 
LEFT JOIN TEST_TABLE2 N  ON M.ID_PK=N.ID_FK 
END

其中@count应该等于从test_table2 group中选择count(name),返回一组列,@ count应该一次取一列值

3 个答案:

答案 0 :(得分:1)

这是另一种方式。如果想法根据TestTable2中是否有重复项而以不同方式显示名称,那么这将起作用:

DECLARE @Count int
SELECT @Count = COUNT(name) FROM test_table2 GROUP BY name HAVING COUNT(name) > 1

INSERT INTO #temp_cols  
SELECT 
   M.ID_PK,  
   CASE 
      WHEN @Count > 1 THEN SUBSTRING(M.NAME, 1, 1) + '_' + N.NAME
      ELSE N.Name
   END,    
FROM TEST_TABLE1 M WITH (NOLOCK) 
  LEFT JOIN TEST_TABLE2 N  ON M.ID_PK = N.ID_FK 

编辑:另一方面,如果TestTable2中有匹配的ID,目的是更改名称的显示,这将起作用并且非常简单:

INSERT INTO #temp_cols  
SELECT 
   M.ID_PK,  
   ISNULL(SUBSTRING(M.NAME, 1, 1) + '_' + N.NAME, M.Name) As Name   
FROM TEST_TABLE1 M WITH (NOLOCK) 
  LEFT JOIN TEST_TABLE2 N  ON M.ID_PK = N.ID_FK

答案 1 :(得分:1)

我创建了一些这样的测试数据:

 id_pk | name | id_fk |  name  
-------+------+-------+--------
     1 | foo  |     1 | jingle
     1 | foo  |     1 | jangle
     2 | bar  |     2 | jangle
     3 | quux |       | 

并写了一个查询:

select m.id_pk, case when groupcount.name_count > 1 then substring(m.name, 1, 1) + '_' + n.name else m.name end
from test_table1 m
  left join test_table2 n on m.id_pk = n.id_fk
  left join (select name, count(name) as name_count from test_table2 group by name) groupcount on n.name = groupcount.name

这产生了这个:

 id_pk |   name   
-------+----------
     1 | foo
     1 | f_jangle
     2 | b_jangle
     3 | quux

我认为你的“else”分支可能意味着m.name而不是n.name?

猜测(这就是为什么示例输出会有用)来自“@count应该一次取一个列值”,你需要从中获取@count test_table2中每个名称的行数。

我相信那个查询的输出就是你要进入临时表的内容:在这种情况下,在它前面添加“insert into #temp_cols”。

答案 2 :(得分:0)

IF EXISTS (select count(name) from test_table2 group by name HAVING count(name) > 1)
BEGIN
  insert into #temp_cols  
  SELECT M.ID_PK,  
  substring(M.NAME,1,1)+'_'+ N.NAME 
  FROM TEST_TABLE1 M WITH (NOLOCK) 
  LEFT JOIN TEST_TABLE2 N  ON M.ID_PK=N.ID_FK  
END

ELSE
BEGIN
  insert into #temp_cols  
  SELECT M.ID_PK,  
  N.NAME 
  FROM TEST_TABLE1 M WITH (NOLOCK) 
  LEFT JOIN TEST_TABLE2 N  ON M.ID_PK=N.ID_FK 
END