Rows to columns SQL Server query
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:
table MAS:
MA SN开发者_Go百科 Mindex
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 ma1, MAS ma2, MAS ma3
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
精彩评论