从一列查询多个值

时间:2014-05-14 16:57:32

标签: sql sql-server sql-server-2008

SQL的新手,我正在努力解决查询,使列中的多个值计数并加在一起。这是查询

select count (*) as NEWCOL
from table1
where COL1 = 'val1' and COL2 = 'val1' and COL3='val1' or 'val2'

2 个答案:

答案 0 :(得分:0)

你的情况看起来有缺陷:

select count (*) as NEWCOL
  from table1
  where COL1 = 'val1'
    and COL2 = 'val1'
    and (COL3 = 'val1' or COL3 = 'val2')
      ;

答案 1 :(得分:0)

试试这个:

SELECT 
  COUNT(y.*) as NewCol
  ,x.[allfields] as WhatyouWantitToBe
FROM 
  table1 y
OUTER APPLY
  (SELECT 
     x.col1 + ' ' + x.col2 + ' ' + x.col3 AS [allFields]
   FROM
     table1 x
   WHERE
     x.col1 = y.col1
     AND
       x.col2 = y.col2
     AND
       x.col3 = y.col3) AS x
WHERE 
  y.COL1 = 'val1'
  AND y.COL2 = 'val1'
  AND (y.COL3 = 'val1' 
       OR 
       y.COL3 = 'val2')

然后再说一遍,你所提到的可以做些什么。 varchar字段的连接以及计数。