按问题分组

时间:2010-10-22 12:25:44

标签: sql sql-server sql-server-2005 tsql

我需要分组,即使通过转换为文本值并且需要将该文本值包含在选择列表中而使列的值存在差异

这怎么可能?

  SELECT col1,col2
   FROM
       (
         SELECT col1,col2 FROM table1
         UNION ALL
     SELECT col1,col2 FROM table2
         UNION ALL
         SELECT col1,col2 FROM table3

       )tbl
  GROUP BY  tbl.col1
           ,tbl.col2

这里col2可能是也可能不是文本值或int,如果是文本值我需要将所有其他col2 int转换为文本并按

进行分组

见这个例子:

Table 1
-------
A B  3   C 
A B  var C


Table 2
-------
UNION ALL

B B  3   C 
B B  var C


Table 3
-------
UNION ALL

B B  3   C 
B B  3   C

Result of each table should be 
-------

Table 1
-------
A B  var C (since there is a var in the any of the row in that column in that table)

Table 2
-------
B B  var C (since there is a var in the any of the row in that column in that table)

Table 3
-------
B B  3   C  (here it remains 3 since there is not value call var in any of the row in that column)

Result 
------
A B  var C
B B  var C  (since there is a var in the any of the row in that column in that table)

2 个答案:

答案 0 :(得分:0)

这似乎有点容易,也许我错过了什么?你只是想在col2上做CAST吗?

SELECT  col1
       ,CAST(col2 AS nvarchar(100)) as Col2
       ...etc

答案 1 :(得分:0)

采取这个:

 SELECT col1,col2
   FROM
       (
         SELECT col1,col2 FROM table1
         UNION ALL
     SELECT col1,col2 FROM table2
         UNION ALL
         SELECT col1,col2 FROM table3

       )tbl
where col2 not like '3%'
  GROUP BY  tbl.col1

结果看起来像你的问题:

B var C

B B var C