Sto usando SQL-Server 2008. Ho bisogno di combinare le righe con la stessa Name
e aumento contatore quando:Combina righe se il valore è vuoto
- 1 o più
Id's
per lo stessoName
èblank
- Non unire righe se
Id
èNULL
! - NON unire righe se abbia la stessa
Name
, ma diversiIds
Uscita per ora:
Name Id Cnt
John 1 1
Peter 2 2 -- This Peter with the same Id have 2 entries so Cnt = 2
Peter 3 1 -- This is other Peter with 1 entry so Cnt = 1
Lisa 4 1
Lisa NULL 1
David 5 1
David 1 -- here Id is blank ''
Ralph 2 -- Ralph have both rows with blank Id so Cnt = 2
output desiderato:
Name Id Cnt
John 1 1
Peter 2 2
Peter 3 1
Lisa 4 1
Lisa NULL 1 -- null still here
David 5 2 -- merged with blank '' so Cnt = 2
Ralph 2 -- merged both blanks '' so Cnt = 2
SQL-Query :
Si tratta di query di esempio quello che sto usando per ora:
SELECT Name,
Id,
COUNT(Id) AS Cnt
FROM Employees
WHERE Condition = 1
GROUP BY Name, Id
Quello che ho cercato:
Aggiunto aggregato MAX
-Id
in SELECT
clausola e raggruppati da solo Name
, ma in questo caso le righe unite con i valori NULL
e con gli stessi nomi con diverso Id's
cosa c'è che non va.
SELECT Name,
MAX(Id), -- added aggregate
COUNT(Id) AS Cnt
FROM Employees
WHERE Condition = 1
GROUP BY Name -- grouped by Name only
Avete qualche idea? Se qualcosa non è chiaro sul problema - chiedimi, fornirò maggiori dettagli.
UPDATE:
DDL
CREATE TABLE Employees
(
Name NVARCHAR(40),
Id NVARCHAR(40)
);
DML
INSERT INTO Employees VALUES
('John' , '1')
,('Peter', '2')
,('Peter', '2')
,('Peter', '3')
,('Lisa' , '4')
,('Lisa' , NULL)
,('David', '5')
,('David', '')
,('Ralph', '')
,('Ralph', '')
DEMO:SQL FIDDLE
+1 per una domanda ben formata. tuttavia, è meglio includere le tabelle rilevanti ddl + dml per i dati di esempio in modo che chiunque voglia rispondere sia in grado di riprodurlo facilmente. –
Progettazione strana di dati nella tabella ... Prenderesti in considerazione i dati di modifica? – Anton
@ZoharPeled secondo, fornirò DDL + DML –