精典SQL语句

前段时间因为找工作的原因,不得不被动的深入学习了数据库,尤其是复杂的SQL语句,感觉自己提升了不少,今天把几个精典的例子拿出来跟大家共同分享,希望对大家能有所帮助。

<!-- 删除表中的有重复行的数据(行中的每一列的值都重复)-->
 select distinct * into #temp from  s drop table s
 select distinct * into s from #temp drop table #temp

 <!-- 根据表中的某一列,删除表中该列所有重复的值->
  select identity(int,1,1) as autoID, * into #Tmp from tableName
  select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoID
  select * from #Tmp where autoID in(select autoID from #tmp2)

<!--精典例题->
 --表结构:
 Date            SaleBuy        quantity            ProductID
 20071211          S              1000                 1
 20080420          S              2000                 1
 20071211          B              3500                 2
 20080420          B              4800                 1
 20071211          S              2300                 2
 20071211          S              5400                 2
 20071211          B              2400                 2

-所要结果如下:
 Date            SaleBuy        quantity            ProductID
 20071211          1000            0                   1
 20071211         7700           5900                 2
 20080420         2000           4800                 1

--解决方法:
 1:
Select date,
        sum(CASE saleBuy WHEN 's' THEN quantity ELSE 0 END) as saleQuantity,
        sum(CASE saleBuy WHEN 'b' THEN quantity ELSE 0 END) as buyQuantity,
        productId
from sale group by date, productId order by date, productId
 2:
select date,saleBuy,sum(quantity) as qu1,productId as p1 into #temp from sale
group by date,saleBuy,productId
select s.date,s.qu1,qu2=(case when b.qu1 is NULL then 0 else b.qu1 end ),s.p1 from
(select date,saleBuy,qu1,p1 from #temp where saleBuy='s')as s
 left join (select date,saleBuy,qu1,p1 from #temp where saleBuy='b')as b
on s.p1=b.p1 and s.date=b.date

-如何求出同一表中不同列的值相同的数量
select sum(case when a1='1' and b1='2' then 1 else 0 end)+sum(case when a2 ='1' and b1='2' then 1 else 0 end)+sum(case when a3 ='1' and b1='2' then 1 else 0 end) as countz from kaka

 ---如何根据某列的值 按主义排序如‘aceb’,'abce'
 select * from sale order by charindex(name,'中华人民共和国')

-从几个列中找出值最大的那一列的值,并赋值给该表中的其它列
update AthleteResult
set GraspResult=(select (case
   when Grasp1 < Grasp2 then Grasp2
   when Grasp1<Grasp3 then Grasp3
   else Grasp1 end)as Grasp from AthleteResult),
    ErectResult=(select (case
  when Erect1<Erect2 then Erect2
  when Erect1 <Erect3 then Erect3
  else Erect1 end) as Erect from AthleteResult)

  <!-- 随机从表中抽取10条记录->
select top 10 * from [table name] order by newid()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abeniaj0427

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值