SQL并排显示详细信息和总计数

时间:2015-08-22 02:32:30

标签: sql sql-server

create table Animal (
Animal varchar(50)
,AnimalID varchar(50)
)
insert into Animal values ('Dog', 'Morning')
insert into Animal values ('Cat', 'Morning')
insert into Animal values ('Turtle', 'Morning')
insert into Animal values ('Dog', 'Evening')
insert into Animal values ('Turtle', 'Evening')
insert into Animal values ('car', 'Afternoon')
insert into Animal values ('Turtle', 'afternoon')
select * from Animal

如何并排获得以下结果?

Dog Morning           Morning     3
Cat Morning           Afternoon  2    
Turtle  Morning           Evening    2 
Dog Evening
Turtle  Evening
car Afternoon
Turtle  afternoon

1 个答案:

答案 0 :(得分:0)

这基于随机排序加入两个结果集(因为没有指定顺序)。

;WITH cte1 AS
(
   SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) rw,*
   FROM Animal
)
,cte2 AS
(
   SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) rw, COUNT(*) cnt, AnimalID
   FROM Animal GROUP BY AnimalID
)

SELECT
   c1.Animal,
   c1.AnimalID,
   c2.AnimalID,
   c2.cnt
FROM cte1 c1 LEFT OUTER JOIN cte2 c2 ON c1.rw = c2.rw