2016-03-09 13 views
7

voglio creare il seguente output da sotto:T-SQL - ottenere dati in base a due colonne

dati

sample

L'ingresso è da una vista (Select * from test). L'obiettivo è quello di ottenere tutti i dati in cui la colonna progress contiene il testo tbd e il numero counter è 1.

Questo può essere risolto con il caso quando la dichiarazione?

Dato sqlfiddle non funziona ecco lo schema:

CREATE TABLE test 
(
    [ID] [int] NOT NULL, 
    [Counter] [int] NOT NULL, 
    [Name] nvarchar(200) NULL, 
    [Progress] nvarchar(200) NOT NULL 
) 

INSERT INTO test 
VALUES (1, 1, 'userA', 'tbd'), 
     (1, 2, 'userB', 'done'), 
     (1, 3, 'userC', 'tbd'), 
     (2, 1, 'userB', 'done'), 
     (2, 5, 'userA', 'tbd'), 
     (3, 1, 'userD', 'tbd'), 
     (3, 2, 'userA', 'done'), 
     (3, 7, 'userC', 'tbd'), 
     (3, 11, 'userB', 'tbd') 

non ho potuto farlo funzionare.

Spero che tu possa darmi una mano.

Grazie mille.

risposta

2

Utilizzando Exists clausola è possibile ottenere il risultato desiderato.

Query

SELECT 
    * 
FROM test t 
WHERE EXISTS (SELECT 1 FROM test 
      WHERE t.ID = ID 
      AND progress = 'tbd' 
      AND counter = 1) 

Risultato

ID Counter Name Progress 
----------------------------- 
1  1  userA tbd 
1  2  userB done 
1  3  userC tbd 
3  1  userD tbd 
3  2  userA done 
3  7  userC tbd 
3  11 userB tbd 

E un altro soluzione alternativa è semplice SELF JOIN come questo-

Query

SELECT 
    le.ID, le.Counter, le.Name, le.Progress 
    FROM test le 
INNER JOIN test re ON le.ID = re.ID 
WHERE re.progress = 'tbd' 
    AND re.counter = 1 

Sopra la query restituisce lo stesso risultato.

+1

perché? un semplice DOVE è sufficiente ... – Vland

+0

@Vland: Simple 'WHERE' fornisce solo 2 righe che non sono l'output desiderato da OP. Puoi verificarlo da solo usando lo script fornito dall'OP in questione. –

+0

ok mio male. Ho pensato che _get tutti i dati in cui la colonna di progresso contiene il testo tbd e il numero del contatore è 1_ significava solo il recupero di 2 righe! grazie per lui ha pubblicato uno screenshot – Vland

1

semplicemente provare:

select * from test where progress = 'tbd' and counter = 1 
1

Forse questo ti aiuterà a:

select *, 
     row_number() over(partition by Progress order by Counter) 
     rowID 
into #tmp 
from Test 

select * 
from #tmp 
where ID in(
      select ID 
      from #tmp 
      where Counter = 1 
        and Progress = 'tbd' 
     ) 
order by ID, 
      rowID 
Problemi correlati