SQL Query: retrieve rows that have a record for each unique column value

Background:

I performed a price search three different times for different objects. These searches are stored in a table with their respective search time, property name and price.

I would like to compare the value of objects over time, but I only want to pull objects that have prices or were available, during all three searches.

In another way, I want to request all the prices over time for a product, but only if this product has a price for all time periods (and I don’t know how many time periods are in advance - it needs to be determined dynamically from the table).

My plan is to use SQL for this (try SQL for the first time ... Maybe this is inappropriate for this task?)

Sample data:

+----------+----------+----------+----------+
| Time     | Item     | Price    | Dummy    |
+----------+----------+----------+----------+
| 1:00 PM  | Toy      | 100      | 1        |
| 1:00 PM  | Cola     | 200      | 2        |
| 1:00 PM  | Book     | 300      | 3        |
| 2:00 PM  | Toy      | 100      | 4        |
| 2:00 PM  | Book     | 250      | 5        |
| 3:00 PM  | Toy      | 100      | 6        |
| 3:00 PM  | Cola     | 250      | 7        |
| 3:00 PM  | Book     | 200      | 8        |
+----------+----------+----------+----------+

:

+----------+----------+----------+----------+
| Item     | 1:00 PM  | 2:00 PM  | 3:00 PM  |
+----------+----------+----------+----------+
| Toy      | 100      | 100      | 100      |
| Book     | 300      | 250      | 200      |
+----------+----------+----------+----------+

(Cola , 2:00 PM)

SQLfiddle : http://www.sqlfiddle.com/#!2/61046/1

! !

+4
2

SQL- , . .

, . , . having time :

select item, group_concat(price order by time) as prices
from tablename
group by item
having count(price) = (select count(distinct time) from tablename)
+1

MySQL? PostgreSQL ( Oracle ) - :

WITH better_format as (
  SELECT  a.Item, a.Time, a.Price, count(*) over ( partition by a.Item ) as distinct_times
  FROM    tableName a
  GROUP BY a.Item, a.Time, a.Price
)
SELECT * FROM better_format
WHERE distinct_times = (
  SELECT max(distinct_times) from better_format
)

. Oracle PostgreSQL Pivot Crosstab, , . , MySQL .

SQL Fiddle

+2

Source: https://habr.com/ru/post/1543144/


All Articles