Transposing data from table with two columns

Query to create table and insert data

CREATE DATABASE [MYTEST]

USE [MYTEST]
GO
/****** Object:  Table [dbo].[MANYTOMANY]    Script Date: 3/21/2016 2:02:11 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MANYTOMANY](
[SUBJECT] [varchar](100) NOT NULL,
[TEACHER] [varchar](100) NOT NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'A', N'AB')
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'A', N'BC')
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'A', N'CD')
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'B', N'BC')
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'B', N'CD')
GO
INSERT [dbo].[MANYTOMANY] ([SUBJECT], [TEACHER]) VALUES (N'B', N'EF')
GO



QUERY TO TRANSPOSE DATA


with cte as
(SELECT [SUBJECT]
      ,[TEACHER]
 ,row_number() over (partition by [subject] order by teacher) RNK
  FROM [MYTEST].[dbo].[MANYTOMANY])

  select [subject],(select teacher from cte a where a.SUBJECT = cte.SUBJECT and a.RNK =1) 'teacher1' ,
  (select teacher from cte a where a.SUBJECT = cte.SUBJECT and a.RNK =2) 'teacher2' ,
  (select teacher from cte a where a.SUBJECT = cte.SUBJECT and a.RNK > 2) 'more than 2 teachers' --,
  from cte
  group by SUBJEC

T-SQL LEAD LAG and SUM function based query

  Query on T-SQL window clause Below is the sales table Order_Date Name Product SubCategory ...