sql複習--同事面試時遇到的複雜sql語句
表的字段非常簡單,創建表的sql語句如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Exam]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Exam](
[S_date] [datetime] NOT NULL,
[Order_Id] [varchar](50) NOT NULL,
[Product_Id] [varchar](50) NOT NULL,
[Amt] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
END
題目一: 寫一條Sql語句查詢前出100到199的記錄
題目二: 寫一條Sql語句刪除重複[除時間外的所有字段字段相同]的記錄,保留重複記錄中時間最大的記錄
題目三: 一條Sql語句查出年份,1月,2月,3月....12月的列表
題目四: 一條sql語句查詢出年份,本月銷量,上月銷量,環比%,去年同期銷量,同比%列表
由於本人sql甚爛,寫了幾個小時才把前三題做出來,不過在做的同時複習了許多被遺忘的知識。
-- 題一 一條Sql語句 查詢前100到199的記錄
select top 100 * from exam
where s_date<
(
select min(T.s_date) from ( select top 99 s_date from exam order by s_date desc ) as T
)
order by s_date desc
--
-- 題二 一條Sql語句 刪除重複的記錄[時間不重複,其它字段重複]
delete from exam
where s_date not in
(
select T.dt from
(
select order_id,product_id,amt,max(s_date) as dt from exam group by order_id,product_id,amt
) as T
)
--
--題三 一條Sql語句 查年份,1月,2月....12月
select y,sum(c1) as m1,sum(c2) as m2,sum(c3) as m3,sum(c4) as m4,sum(c5) as m5,sum(c6) as m6,
sum(c7) as m7,sum(c8) as m8,sum(c9) as m9,sum(c10) as m10,sum(c11) as m11,sum(c12) as m12
from
(
select
y,
case m when 1 then c else 0 end as c1,
case m when 2 then c else 0 end as c2,
case m when 3 then c else 0 end as c3,
case m when 4 then c else 0 end as c4,
case m when 5 then c else 0 end as c5,
case m when 6 then c else 0 end as c6,
case m when 7 then c else 0 end as c7,
case m when 8 then c else 0 end as c8,
case m when 9 then c else 0 end as c9,
case m when 10 then c else 0 end as c10,
case m when 11 then c else 0 end as c11,
case m when 12 then c else 0 end as c12
from
(
select y,m,count(s_date) as c from
(
select datepart(year,convert(DateTime,s_date)) as y,
datepart(month,convert(DateTime,s_date)) as m ,
s_date from exam
) as T1
group by T1.y,T1.m
)
as T2
) as T3
group by T3.y
第一次寫“文章”,如果有錯誤的地方,還請高手指點!