[英]How to select rows where multiple columns have same values
I have a sql server table named myTbl like this: 我有一个名为myTbl的sql server表,如下所示:
BookID PageID textID Date Remarks
1 4 9 21-12-2017 1
2 5 10 15-12-2017 1
3 6 11 13-12-2017 1
4 7 12 11-12-2017 1
2 5 10 22-12-2017 1
4 7 12 18-12-2017 1
I want to group the rows when BookID, PageID and textID have same values and show the result based on the most recent date ascending. 当BookID,PageID和textID具有相同的值时,我想对行进行分组,并根据最近的日期升序显示结果。 For instance 4th & 6th row and 2nd & 5th row.
例如第4和第6行以及第2和第5行。
What I need is: 我需要的是:
BookID PageID textID Date Remarks
1 4 9 21-12-2017 1
2 5 10 15-12-2017 1
2 5 10 22-12-2017 1
3 6 11 13-12-2017 1
4 7 12 11-12-2017 1
4 7 12 18-12-2017 1
How I want to write is: 我要写的是:
SELECT *
FROM booksdb.dbo.books
GROUP BY BookID, PageID, textID Order by Date
I want all the columns in the table where BookID, PageID, textID are same and arranged by date. 我想要表中的所有列,其中BookID,PageID,textID相同并且按日期排列。
You don't need group by
, Because there is not any aggregate function in your query. 您不需要
group by
,因为查询中没有任何聚合函数 。 you can try to use RANK
with window function to make row_number then order by the number. 您可以尝试将
RANK
与窗口函数配合使用来制作row_number,然后按数字排序。
CREATE TABLE T (
BookID INT,
PageID INT,
textID INT,
DATE DATE,
Remarks INT
);
INSERT INTO T VALUES (1,4,9 ,'2017-12-21',1);
INSERT INTO T VALUES (2,5,10,'2017-12-15',1);
INSERT INTO T VALUES (2,5,10,'2017-12-22',1);
INSERT INTO T VALUES (3,6,11,'2017-12-13',1);
INSERT INTO T VALUES (4,7,12,'2017-12-11',1);
INSERT INTO T VALUES (4,7,12,'2017-12-18',1);
Query 1 : 查询1 :
;WITH CTE AS (
SELECT *,RANK() OVER(PARTITION BY BookID, PageID, textID Order by Date) rn
FROM T
)
SELECT BookID,PageID,textID,[DATE],Remarks
FROM CTE
ORDER BY BookID, PageID, textID,rn
| BookID | PageID | textID | DATE | Remarks |
|--------|--------|--------|------------|---------|
| 1 | 4 | 9 | 2017-12-21 | 1 |
| 2 | 5 | 10 | 2017-12-15 | 1 |
| 2 | 5 | 10 | 2017-12-22 | 1 |
| 3 | 6 | 11 | 2017-12-13 | 1 |
| 4 | 7 | 12 | 2017-12-11 | 1 |
| 4 | 7 | 12 | 2017-12-18 | 1 |
All you seem to need is an ORDER BY
all the columns you mentioned in the order you mentioned them. 您似乎需要的只是按照您提到的所有列的顺序排列
ORDER BY
。
SELECT *
FROM booksdb.dbo.books
ORDER BY bookid,
pageid,
textid,
date;
Edit: 编辑:
Note: If you want the order of the dates to show the youngest one first (eg 18-12-2017 before 11-12-2017), rather than the other way around, change the ORDER BY
clause to: 注意:如果希望日期顺序显示最小的日期(例如,2017年11月18日之前的2017年12月18日),而不是相反,请将
ORDER BY
子句更改为:
ORDER BY bookid,
pageid,
textid,
date DESC;
(Note the DESC
after date
). (请注意
date
后的DESC
)。
The desired result may contradict the description you gave and overall they leave room for interpretation regarding this point. 期望的结果可能与您的描述相抵触,并且总体而言,它们为这一点留下了解释的空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.