用于HAVING COUNT的Oracle SQL命令

drkbr07n  于 2023-06-22  发布在  Oracle
关注(0)|答案(1)|浏览(174)

问题是
任何艺术作品的详细信息沿着创作该作品的艺术家的全名,该作品至少有两个副本记录在数据库中。
我试着使用这个代码,但它什么也没有显示:

SELECT w.WorkID, w.Title, w.Copy, w.Medium, w.Description,
       a.FirstName || ' ' || a.LastName AS ArtistFullName
FROM dtoohey.Work w,
     dtoohey.artist a
WHERE w.ArtistID = a.ArtistID
AND w.WorkID IN (
        SELECT w.WorkID
        FROM dtoohey.Work w
        GROUP BY w.WorkID
        HAVING COUNT(w.copy) > 2
        );

我非常困惑,不知道该为having count添加或更改什么。
数据显示副本如下图所示。
the data shown of the 'copy'
有人能帮我解决这个问题吗?

hs1rzwqc

hs1rzwqc1#

你需要分析你的数据,并计算出哪些是相同的副本。如果WorkID是主键,则只有一行具有该标识符;在这种情况下,您需要使用一些其他方法来检测副本,例如TitleArtistID的组合。
此外,HAVING COUNT(w.copy) > 2将检查是否有三个或更多副本。您希望> 1>= 2检查两个或多个副本。

SELECT w.WorkID,
       w.Title,
       w.Copy,
       w.Medium,
       w.Description,
       a.FirstName ||' '|| a.LastName AS ArtistFullName
FROM   dtoohey.Work w
       INNER JOIN dtoohey.artist a
       ON w.ArtistID=a.ArtistID
WHERE  EXISTS (
         SELECT 1
         FROM   dtoohey.Work x
         WHERE  x.artistid = w.artistid
         AND    x.title    = w.title
         GROUP BY x.artistid, x.title
         HAVING COUNT(*) > 1
       );

您还可以使用分析函数来计算重复项:

SELECT w.WorkID,
       w.Title,
       w.Copy,
       w.Medium,
       w.Description,
       a.FirstName ||' '|| a.LastName AS ArtistFullName
FROM   ( SELECT w.*,
                COUNT(*) OVER (PARTITION BY artistid, title) AS cnt
         FROM   dtoohey.Work w
       ) w
       INNER JOIN dtoohey.artist a
       ON w.ArtistID=a.ArtistID AND cnt > 1;

其中,对于样本数据:

CREATE TABLE dtooney.work (workid, title, copy, medium, description, artistid) AS
SELECT 1, 'Finger Painting', '1/5', 'Acrylic on Paper', 'Finger Painting', 1 FROM DUAL UNION ALL
SELECT 2, 'Finger Painting', '4/5', 'Acrylic on Paper', 'Finger Painting', 1 FROM DUAL UNION ALL
SELECT 3, 'The Scream', '1/1', 'Wool', 'Knitted version of The Scream', 2 FROM DUAL UNION ALL
SELECT 4, 'Half a Cow', '1/2', 'Taxidermy', 'Front Half', 3 FROM DUAL UNION ALL
SELECT 5, 'Half a Cow', '2/2', 'Taxidermy', 'Left Half', 3 FROM DUAL;

CREATE TABLE dtooney.artist (artistid, firstname, lastname) AS
SELECT 1, 'Alice', 'Abbot' FROM DUAL UNION ALL
SELECT 2, 'Betty', 'Baron' FROM DUAL UNION ALL
SELECT 3, 'Carol', 'Count' FROM DUAL;

两个输出:
| 工作ID|标题|副本|中等|说明|艺术家全名|
| - -----|- -----|- -----|- -----|- -----|- -----|
| 1|手指画|五分之一|纸上亚克力|手指画|爱丽丝·艾博特|
| 2|手指画|4/5|纸上亚克力|手指画|爱丽丝·艾博特|
| 4|半头牛|1/2|动物标本剥制术|前半部分|卡罗尔伯爵|
| 5个|半头牛|2/2|动物标本剥制术|左半部分|卡罗尔伯爵|
fiddle

相关问题