获取不同记录的问题(分组)

时间:2017-01-24 18:50:22

标签: sql sql-server group-by distinct

我无法获得不同的记录。这是我的查询。

SELECT DISTINCT TOP (100) PERCENT
dbo.New_BookList.author, dbo.issued.issued, dbo.Ath_Crs_New.SUBJECT, dbo.New_BookList.isbn, dbo.New_BookList.title
FROM dbo.New_BookList
LEFT OUTER JOIN dbo.Ath_Crs_New
ON dbo.New_BookList.catalog_Number = dbo.Ath_Crs_New.CATALOG_NUMBER
AND  dbo.New_BookList.emplid = dbo.Ath_Crs_New.EMPLID
LEFT OUTER JOIN dbo.issued ON dbo.New_BookList.emplid = dbo.issued.emplid
AND dbo.New_BookList.isbn = dbo.issued.itemnum
AND dbo.New_BookList.term = dbo.issued.term
WHERE (dbo.New_BookList.book_status <> 'cancelled')
AND (dbo.New_BookList.emplid = 227698467)
AND (dbo.New_BookList.term = 1172)
ORDER BY dbo.New_BookList.isbn

以下是我得到的输出:

+------------+--------+---------+---------------+--------------------------------+
|   Author   | Issued | Subject |     ISBN      |             Title              |
+------------+--------+---------+---------------+--------------------------------+
| ALPERT     | False  | REL     | 9780231165716 | RELIGION & SPORTS              |
| TOP HAT    | False  | EAR     | 9780986615108 | MONOCLE CAT SEMESTER           |
| TOP HAT    | False  | IST     | 9780986615108 | MONOCLE CAT SEMESTER           |
| KING       | False  | CFS     | 9781269910842 | HUMAN SEXUALITY TODAY PACKAGE  |
| PEARSON ED | False  | CFS     | 9781269952460 | MYPSYCHLAB FOR KING HUMAN SEXU |
| KING       | False  | CFS     | 9781269954280 | HUMAN SEXUALITY TODAY CUSTOM F |
| DUARTE     | False  | IST     | 9781422187104 | HBR GUIDE TO PERSUASIVE PRESEN |
| MILLER     | False  | IST     | 9781541800861 | PROGRAMMING IN PYTHON 3 ACCESS |
| ARNOLD     | False  | REL     | 9781935551218 | GIFT OF SPORTS - REVISED (LOOS |
+------------+--------+---------+---------------+--------------------------------+

我的问题在于Monacle CAT学期书。由于两个副本上的ISBN号相同,所以如果已经列出,我只想显示一次。因此,无论主题如何,我都需要通过ISBN对此进行分组。

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:3)

您可以对结果进行分组,并按字母顺序选择MAX或MIN主题。

SELECT DISTINCT TOP (100) PERCENT 
    dbo.New_BookList.author
    , dbo.issued.issued
    , MAX(dbo.Ath_Crs_New.SUBJECT) AS [SUBJECT]
    , dbo.New_BookList.isbn
    , dbo.New_BookList.title
FROM         
    dbo.New_BookList LEFT OUTER JOIN
                  dbo.Ath_Crs_New ON dbo.New_BookList.catalog_Number = dbo.Ath_Crs_New.CATALOG_NUMBER AND 
                  dbo.New_BookList.emplid = dbo.Ath_Crs_New.EMPLID LEFT OUTER JOIN
                  dbo.issued ON dbo.New_BookList.emplid = dbo.issued.emplid AND dbo.New_BookList.isbn = dbo.issued.itemnum AND 
                  dbo.New_BookList.term = dbo.issued.term
WHERE     (dbo.New_BookList.book_status <> 'cancelled') AND (dbo.New_BookList.emplid = 227698467) AND (dbo.New_BookList.term = 1172)
GROUP BY
    dbo.New_BookList.author
    , dbo.issued.issued
    , dbo.New_BookList.isbn
    , dbo.New_BookList.title
ORDER BY dbo.New_BookList.isbn