Element repeated at least 3 times

不羁的心 提交于 2019-12-24 15:27:50

问题


Is there a way to tell if an element is at least 3 times in a column without using Count and Group By?

EDIT: The answer is expected in SQL (mysql or oracle11g) in which only SELECT, FROM, WHERE and JOINS are used. And of course, all the logical operators and quantifiers as RELATIONAL CALCULUS WITH TUPLES has NO tools at all.

Example of tuples:

{ t : {name} | ∃ s : {name, wage} ( Employee(s) ∧ s.wage = 50.000 ∧ t.name = s.name ) }

here, the limitations of Relational Calculus with tuples are clear.

No CTE's, no group by, no row tools, no distinct, no count, no views, no create, no insert, no alter. None of those awesome SQL tools.

The reason why I don't want to use Count and Group By is because I'll take this to Relational Calculus with Tuples, which doesn't allow those tools.

As an example:

Suppose there is a table ORDER (Id_article, Id_Provider) where both ID's are foreign keys.

Query: Get all the articles that were ordered at least 3 times.

Let the table ORDER be:

   Id_Article      Id_Provider

       1               A
       1               B
       1               B
       2               C
       2               C
       3               A

The result of the query should be only the element 1, as it is 3 times in Id_Article.


回答1:


Down know if this answer your question. But oracle have a row_number function

In this case partition_by restart the counting with each article.

SQL Fiddle Demo

WITH CTE AS (
  SELECT    "Id_Article", 
            "Id_Provider", 
            ROW_NUMBER() OVER 
            (PARTITION BY "Id_Article" ORDER BY "Id_Provider")  AS rn
      FROM  Table1
)     
SELECT DISTINCT "Id_Article"
FROM CTE
WHERE rn >= 3;



回答2:


Possible solution:

Let's call the following Ids

SELECT O1.id_article AS id FROM ORDER O1 JOIN ORDER O2 ON O1.id_article = O2.id_article MINUS SELECT O3.id_article AS id FROM ORDER O3 MINUS SELECT O3.id_article AS id FROM ORDER O3 MINUS SELECT O3.id_article AS id FROM ORDER O3 MINUS SELECT O3.id_article AS id FROM ORDER O3

Then our relational equation is { t : {id} | ∃ s : {id} ( Ids(s) ∧ t.id = s.id ) }

If you can't use MINUS, then maybe this can help Converting aggregate operators from SQL to relational algebra



来源:https://stackoverflow.com/questions/32556972/element-repeated-at-least-3-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!