Domanda

Supponi di avere un recordset come il seguente:

| ID  | Foo  | Bar  | Red  |
|-----|------|------|------|
| 1   | 100  | NULL | NULL |
| 1   | NULL | 200  | NULL |
| 1   | NULL | NULL | 300  |
| 2   | 400  | NULL | NULL |
| ... | ...  | ...  | ...  | -- etc.

E tu vuoi:

| ID  | Foo | Bar | Red |
|-----|-----|-----|-----|
| 1   | 100 | 200 | 300 |
| 2   | 400 | ... | ... |
| ... | ... | ... | ... | -- etc.

Puoi usare qualcosa del tipo:

SELECT
  ID,
  MAX(Foo) AS Foo,
  MAX(Bar) AS Bar,
  MAX(Red) AS Red
FROM foobarred
GROUP BY ID

Ora, come potresti ottenere risultati simili quando Foo, Bar e Red sono VARCHAR?

| ID  | Foo      | Bar     | Red     |
|-----|----------|---------|---------|
| 1   | 'Text1'  | NULL    | NULL    |
| 1   | NULL     | 'Text2' | NULL    |
| 1   | NULL     | NULL    | 'Text3' |
| 2   | 'Test4'  | NULL    | NULL    |
| ... | ...      | ...     | ...     | -- etc.

A:

| ID  | Foo      | Bar     | Red     |
|-----|----------|---------|---------|
| 1   | 'Text1'  | 'Text2' | 'Text3' |
| 2   | 'Text4'  | ...     | ...     |
| ... | ...      | ...     | ...     | -- etc.

Attualmente funziona principalmente con SQL Server 2000; ma hanno accesso ai server del 2005.

È stato utile?

Soluzione

Non ho accesso a una casella SQL2K al momento, ma seleziona max (colonna) funzionerà su nvarchars nel 2005. L'unico problema sarà se hai più valori di testo sotto ogni colonna per ogni ID nella tabella originale ...

CREATE TABLE Flatten (
    id int not null,
    foo Nvarchar(10) null,
    bar Nvarchar(10) null,
    red Nvarchar(10) null)

INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, 'Text1', null, null)
INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, 'Text2', null)
INSERT INTO Flatten (ID, foo, bar, red) VALUES (1, null, null, 'Text3')
INSERT INTO Flatten (ID, foo, bar, red) VALUES (2, 'Text4', null, null)



SELECT 
    ID, 
    max(foo),
    max(bar),
    max(red)
FROM
Flatten
GROUP BY ID

ritorna

ID          Foo        Bar        Red
----------- ---------- ---------- ----------
1           Text1      Text2      Text3
2           Text4      NULL       NULL

Altri suggerimenti

La query di cui sopra funziona bene per i campi VARCHAR come per i campi INT. Il problema con la tua query è che se hai due righe con lo stesso ID, ed entrambe le righe avevano qualcosa nella sezione "Foo" colonna, quindi verrà visualizzato solo quello con il valore più alto (sia per INT che per VARCHAR).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top