How to select only the rows that have a column with a repeated value?

时间:2015-07-28 16:24:29

标签: android sql sqlite

I am building an Android app for a bus schedule between my village and Barcelona.

I have built a sqlite database as follows (probably it's a really bad design, but I'm a newbie in databases):

run | stopCode | time
1.........1.......620
1.........2.......650
.
.
.
5........11.......NULL
5........12.......1020

And so on.

I use the following SQL statement in order to pick the rows that match my criteria:

 SELECT run,stopCode,time
 FROM tablename
 WHERE time> x AND time <>'' AND (stopCode=1 or stopCode=8);

Using this sentence gives me an output similar to this:

6(run)|8(stopCode)|1045(time)
9|1|1900
9|8|2000

My problem is that I want to select only the rows that have the run value repeated twice. If it only appears once, it means that the bus has a NULL destination in that particular run.

I tried using COUNT(*) c, blabla c=2, but that gives me only the second row with the repeated run number, and I want to select both of them (which would correspond to where you pick the bus and where you want to go down). Any clues how to do it?

Edit:

this is the statement i tried

SELECT run,stopNumber,time,COUNT(run) c 
FROM Directes_dirBarna 
WHERE time> 600 and time<>'' and (stopNumber=1 or stopNumber=8) 
GROUP BY run having c=2; 

Edit2:

Thanks to Marcos Vasconcelos i fixed it. This is my final statement if anyone has the same problem:

SELECT run,parada, hora FROM Directes_dirBarna taula WHERE hora> 600
and TIME<>'' IN (parada=1, parada=8);

3 个答案:

答案 0 :(得分:0)

I don't have enough reputations to add it as a comment. If I understand correctly what the question is, to select runs that are 5 or 8 and that should be more than once in the table with some constraints on time. For that the solution is

SELECT a.run, a.stopNumber,time 
FROM Directes_dirBarna a, Directes_dirBarna b 
WHERE a.run = b.run AND (a.run= 5 or a.run = 8) AND time> 600 and time<>'';

remove (a.run= 5 or a.run = 8) if you want any run that repeated twice.

答案 1 :(得分:0)

Here you go:

select t1.run, t1.code, t2.code from tablename t1, tablename t2
    where t1.run = t2.run and t1.code = 1 and t2.code = 8;

You select 2 rows (t1 and t2) such as they are on the same run, one is the departure, and one is the arrival. It will give you a single line for each run that satisfies the condition.

See http://sqlfiddle.com/#!5/7d3f3/3

答案 2 :(得分:0)

您可以使用IN运算符并重复查询(但如果有其他选项可用则会很糟糕)

相关问题