如何将select语句拆分为多个表?

时间:2015-09-15 07:34:38

标签: sql sql-server sql-server-2008 select sql-server-2012

我正在使用select语句检索结果,如下所示

ID  Name    CASETYPE 
1   Anil    TR
2   Sam     CR
3   Samuel  TR
4   Satish  CR
5   Kumar   CI

我的查询是:

SELECT max(ID),max(Name),casetype FROM TABLE GROUP BY CASETYPE

预期OutPut:

表1

ID  Name    CASETYPE 
1   Anil    TR
2   Samuel  TR

表2

ID  Name    CASETYPE    
1   Sam     CR  
2   Satish  CR

表3

ID  Name    CASETYPE    
1   Kumar   CI  

4 个答案:

答案 0 :(得分:1)

我不知道你为什么要这样做。但这是使用CURSOR和动态SQL的一种方式:

DECLARE @caseType VARCHAR(2)
DECLARE @sql NVARCHAR(MAX)

DECLARE cur CURSOR LOCAL FAST_FORWARD FOR
    SELECT DISTINCT CaseType FROM tbl ORDER BY CaseType DESC

OPEN cur
FETCH FROM cur INTO @caseType

WHILE @@FETCH_STATUS = 0 BEGIN
    SET @sql = 'SELECT ID = ROW_NUMBER() OVER(ORDER BY ID), Name, CaseType FROM tbl WHERE CaseType = @caseType'

    EXEC sp_executesql @sql, N'@caseType VARCHAR(2)', @caseType

    FETCH FROM cur INTO @caseType
END

CLOSE cur
DEALLOCATE cur

答案 1 :(得分:1)

我不明白你希望你的当前查询如何为每个casetype返回超过1行,aggrigates每个casetype只返回1行。

无法将select拆分为不同的表。试试这个:

CREATE table table1(ID int identity(1,1), Name varchar(10), CASETYPE char(2))
CREATE table table2(ID int identity(1,1), Name varchar(10), CASETYPE char(2))
CREATE table table3(ID int identity(1,1), Name varchar(10), CASETYPE char(2))

INSERT table1(Name, CASTTYPE)
SELECT Name, CASETYPE 
FROM yourtable
WHERE CASETYPE = 'TR'


INSERT table2(Name, CASTTYPE)
SELECT Name, CASETYPE 
FROM yourtable
WHERE CASETYPE = 'CR'

INSERT table3(Name, CASTTYPE)
SELECT Name, CASETYPE 
FROM yourtable
WHERE CASETYPE = 'CI'

答案 2 :(得分:0)

begin
Declare @temp1 Table
(
  caseType varchar(2)
)
Declare @ResultTable  Table
(
  id int,
  name varchar(50),
  casetype varchar(2)
)
Insert into @temp1 
select distinct casetype from Table_1
Declare @caseType varchar(2)
While((Select Count(*) From @temp1)>0)
Begin
   Set @caseType=(Select Top 1 casetype From @temp1)

   Insert Into @ResultTable 
   select * from Table_1 Where casetype=@caseType

   select * from @ResultTable

   delete from @ResultTable
   Delete @temp1 Where caseType=@caseType
End
end

答案 3 :(得分:0)

DECLARE @CaseTypeCount TINYINT           --Variable to store the Distinct case type count 
DECLARE @IteratorForCaseType TINYINT = 1 --Iterator for looping

/* get the ditinct case type count */
SELECT @CaseTypeCount = COUNT(DISTINCT CASETYPE) FROM YourTable

/* Loop for all distinct case types */
WHILE (@IteratorForCaseType<= @CaseTypeCount)
BEGIN
/* Use a Common table expression to manipulate thetemperory results */
;WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY CASETYPE DESC) AS RowID,
CASETYPE
FROM
YourTable
GROUP BY
CASETYPE
)

SELECT 
ROW_NUMBER() OVER (ORDER BY ID ) AS ID  
,Name
,YourTable.CASETYPE 
FROM CTE
INNER JOIN 
YourTable
ON YourTable.CASETYPE = CTE.CASETYPE
WHERE RowID = @IteratorForCaseType

SET @IteratorForCaseType +=1

END