Question : Query to group sparse data?

Hello,

I have a customer that has come to me with a request for a query that I've never attempted before.  

Certainly I could use VBA to get around doing it with SQL rather easily, but they want a SQL solution without altering the structure of their existing table.

Here is the table layout:

ID    Column1    Column2    Column3    Column4    Column5    ...etc...
1          0                 0               5                0                0
2          7                 0               0                2                0
3          1                 2               3                0                0
...etc...

They want the query output to look like so:

ID    Type1    Type2    Type3
1         5            0           0
2         7            2           0
3         1            2           3

I could also write a really long nasty chain of IIF statements, but i'm looking for something much more elegant.  (There are about 30 columns)

Any thoughts?

-Torrwin

Answer : Query to group sparse data?

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
With ee26366939 as the base table with ID, Col1, Col2, Col3, Col4, Col5
And two helper queries

q26366939:

SELECT
ID,
IIF(Col1=0,null,Col1) AS Col1a,
IIF(Col2=0,null,Col2) AS Col2a,
IIF(Col3=0,null,Col3) AS Col3a,
IIF(Col4=0,null,Col4) AS Col4a,
IIF(Col5=0,null,Col5) AS Col5a
FROM ee26366939;

q26366939a:

SELECT
ID,
nz(Col1a/Col1a,0) as Col1b,
nz(Col1a/Col1a,0)+nz(Col2a/Col2a,0) as Col2b,
nz(Col1a/Col1a,0)+nz(Col2a/Col2a,0)+nz(Col3a/Col3a,0) as Col3b,
nz(Col1a/Col1a,0)+nz(Col2a/Col2a,0)+nz(Col3a/Col3a,0)+nz(Col4a/Col4a,0) as Col4b,
nz(Col1a/Col1a,0)+nz(Col2a/Col2a,0)+nz(Col3a/Col3a,0)+nz(Col4a/Col4a,0)+nz(Col5a/Col5a,0) as Col5b
FROM q26366939;

The final query can be written thus:

SELECT
A.ID,
IIF(Col1B=1,Col1,IIF(Col2b=1,Col2,IIF(Col3b=1,Col3,IIF(Col4b=1,Col4,Col5)))),
IIF(Col1B=2,Col1,IIF(Col2b=2,Col2,IIF(Col3b=2,Col3,IIF(Col4b=2,Col4,Col5)))),
IIF(Col1B=3,Col1,IIF(Col2b=3,Col2,IIF(Col3b=3,Col3,IIF(Col4b=3,Col4,Col5)))),
IIF(Col1B=4,Col1,IIF(Col2b=4,Col2,IIF(Col3b=4,Col3,IIF(Col4b=4,Col4,Col5)))),
IIF(Col1B=5,Col1,IIF(Col2b=5,Col2,IIF(Col3b=5,Col3,IIF(Col4b=5,Col4,Col5))))
FROM ee26366939 AS A
inner join q26366939a As B on A.ID=B.ID;
Random Solutions  
 
programming4us programming4us