zoukankan      html  css  js  c++  java
  • Sqlserver_分组

    create table orders
    (
     id int,
     orderName varchar(100) 
    )
    go
    create table cars
    (
    id int identity(1,1) ,
    ordersid int,
    pname varchar(100),
    pprice varchar(100)
    )
    go
    insert into orders values(10001,'订单1')
    insert into cars values(10001,'商品1','价格1')
    insert into cars values(10001,'商品2','价格2')
    insert into cars values(10001,'商品3','价格3')
    
    insert into orders values(10002,'订单2')
    insert into cars values(10002,'商品21','价格21')
    insert into cars values(10002,'商品22','价格22')
    insert into cars values(10002,'商品23','价格23')
    
    go
    select * from orders
    select * from cars
    go
    select 
    case x.AId when '1' then x.orderName else '' end 订单名称,
    x.pname,x.pprice
       from 
    (
    SELECT   t.*,  dense_rank() OVER (partition BY t.id
                           ORDER BY t.ids ASC) AS AId
                           from
                           (  
    select a.id as ids,b.id,b.orderName,a.pname,a.pprice from cars a inner join orders b on a.ordersid=b.id
    ) as t
    ) as x
    go
    
    CREATE TABLE [dbo].[testTable]  
    (  
    [id] [int] NOT NULL IDENTITY(1, 1),  
    [name] [nchar] (10)  collate Chinese_PRC_CI_AS NULL,  
    [counts] [int] NULL,  
    [createDate] [datetime] NULL  
    )  
    GO  
    -- Constraints and Indexes   
    ALTER TABLE [dbo].[testTable] ADD CONSTRAINT [PK_testTable] PRIMARY KEY CLUSTERED ([id])  
    GO 
    insert into testTable(id,name,counts,createDate) values(1,'A         ',20,'01 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(2,'A         ',10,'02 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(3,'B         ',20,'03 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(4,'B         ',40,'04 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(5,'B         ',10,'05 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(6,'C         ',20,'06 14 2011 10:52PM')  
    insert into testTable(id,name,counts,createDate) values(7,'C         ',40,'07 14 2011 10:52PM')  
    
    select * from (  
     select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn  
     from testTable  
    ) t where t.rn <=1 
  • 相关阅读:
    新博客即将启用
    关于博主 | 联系博主
    结束吧,为这不圆满的故事划上一个残缺的句号
    自用线段树模板
    NOIP 2017 day 1 游记
    NOIP 2017 Day 0. 游记
    NOIP 2017 day -1 杂记
    再一次想不出应该起什么标题
    做图与树做到吐的一天
    自用二分图匹配模板
  • 原文地址:https://www.cnblogs.com/ingstyle/p/4203520.html
Copyright © 2011-2022 走看看