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 some tables I joined together.
Here is an example:
SELECT SUBSTRING(CAST(CAST(HCPD.SeferCikisZamani AS TIME) AS VARCHAR), 1, 5) AS Kalkis, SUBSTRING(CAST(CAST(HCPD.DonusZamani AS TIME) AS VARCHAR), 1, 5) AS Donus, V.AracPlaka
FROM HAT_CALISMA_PLANI HCP WITH(NOLOCK)
INNER JOIN HAT_CALISMA_PLANI_DETAY HCPD WITH(NOLOCK) ON HCPD.HatCalismaPlaniKey = HCP.HatCalismaPlaniKey
INNER JOIN VALIDATOR V WITH(NOLOCK) ON V.ValidatorKey = HCPD.ValidatorKey
WHERE HCP.HatKey = 2 AND CAST(HCPD.SeferCikisZamani AS DATE) = '2012-09-25'
ORDER BY Kalkis
This query returns this result:
Kalkis Donus AracPlaka
-------------------------
01:51 02:01 07 ABY 04
02:02 02:12 07 AB 978
02:21 02:31 07 ABY 04
02:32 02:42 07 AB 978
03:01 03:11 07 ABY 04
03:02 03:12 07 AB 978
03:31 03:41 07 ABY 04
03:42 03:52 07 AB 978
04:01 04:11 07 ABY 04
However, In my report they are supposed to look like this,
07 ABY 04 07 AB 978
Kalkis 06:15 06:30
Donus 07:45 08:00
Kalkis 08:00 08:10
Donus 09:30 09:40
Kalkis 10:00 10:15
Donus 11:30 11:45
Kalkis 12:30 12:45
Donus 14:00 14:15
By the way, these are like bus schedules.
Anyone know a good way to achieve this?
It would be easier to see the data before you queried it, but if you want to use your existing query, you can do the following:
Since you are attempting to
PIVOTtwo columns, the easiest way is toUNPIVOTtheKalkisand theDonuscolumns first, then apply thePIVOTto the data.Here is a SQL Fiddle with Demo (excludes your original query)