I am writing a query that will be used in a .NET application, therefore I would like the SQL Server 2008 o do much of the processing for me instead of the client PC that the application will run on.
I am trying to get data from a single table with an index value, based off of that index value I would like that item to placed in a specific column.
Here is an example:
CREATE TABLE MAS
(
MA CHAR(4),
SN CHAR(6),
Mindex TINYINT
)
INSERT MAS (MA, SN, Mindex)
VALUES
('B275','7A1515',1),
('B276','7A1515',2),
('E530','7A1515',3),
('B291','7A1519',1),
('B292','7A1519',2),
('E535','7A1519',3),
('B301','7A2515',1),
('B302','7A2515',2),
('B331','7A2519',1),
('B332','7A2519',2);
Here is the output I would like:
SN | mi1 | mi2 | mi3 |
---|---|---|---|
7A1515 | B275 | B276 | E530 |
7A1519 | B291 | B292 | E535 |
7A2515 | B301 | B302 | NULL |
7A2519 | B331 | B332 | NULL |
I tried doing the following query, it works with items with 3 indexes but if there are only two, it fills it with random data.
SELECT mas1.SN,
mas1.MA AS mi1,
mas2.MA AS mi2,
mas3.MA AS mi3
FROM MAS mas1,
MAS mas2,
MAS mas3
WHERE mas1.SN = '7A1515'
AND mas1.Mindex = '1'
AND mas2.Mindex = '2'
AND mas3.Mindex = '3'
I was wondering if anyone would be able to point me in the right direction as I am still fairly new at writing these advanced queries.
As you are on SQL Server 2008 you can also use PIVOT
but the old style way of doing it is often easier IMO.
SELECT
SN,
MAX(CASE WHEN Mindex=1 THEN MA END) AS mi1,
MAX(CASE WHEN Mindex=2 THEN MA END) AS mi2,
MAX(CASE WHEN Mindex=3 THEN MA END) AS mi3
FROM MAS
GROUP BY SN
Just for completeness a version with PIVOT
...
SELECT SN,
P.[1] AS mi1,
P.[2] AS mi2,
P.[3] AS mi3
/*Should ensure PIVOT source only projects columns that you want to use
for grouping, aggregation or pivoting so not using MAS directly to avoid
unwanted "extra" implicit grouping columns should table get columns added
*/
FROM (SELECT SN, Mindex, MA FROM MAS) PivotSource
PIVOT (MAX(MA) FOR Mindex IN ([1],[2],[3])) AS P