行到列SQL查询

时间:2012-09-27 10:07:03

标签: sql sql-server pivot

我正在编写一个将在.NET应用程序中使用的查询,因此我希望SQL Server 2008为我做大部分处理,而不是运行应用程序的客户端PC。

我正试图从我加入的一些表中获取数据。

以下是一个例子:

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

此查询返回此结果:

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

但是,在我的报告中,它们看起来应该是这样的,

        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

顺便说一句,这些就像公交时刻表。 有人知道实现这个目标的好方法吗?

1 个答案:

答案 0 :(得分:4)

在查询数据之前查看数据会更容易,但如果要使用现有查询,则可以执行以下操作:

select *
from
(
  select AracPlaka, val, col,
     row_number() over(partition by AracPlaka order by VAL, col) rn
  from
  (
    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
  ) x
  unpivot
  (
    val
    for col in(Kalkis, Donus)
  ) u
) x1
pivot
(
  max(val)
  for AracPlaka In([07 ABY 04], [07 AB 978])
) p

由于您尝试PIVOT两列,最简单的方法是首先UNPIVOT KalkisDonus列,然后应用PIVOT对数据。

这是SQL Fiddle with Demo(不包括原始查询)