将行列结果转换为sql中的行

时间:2013-06-18 07:18:21

标签: sql

我有这样的查询

select convert(date,dtime) as Date, vtid,count(vtid) as count 
from Transaction_tbl 
group by cast(dtime as date),vtid 
order by  cast(dtime as date)

我正在获得输出这个

输出

Date       vtid        count
---------- ----------- -----------
2013-05-07 7           4
2013-05-08 7           5
2013-05-08 8           3
2013-05-08 9           1
2013-05-09 7           3
2013-05-12 8           1
2013-05-13 8           1
2013-05-15 7           1
2013-05-15 9           1

但是我需要在同一行中出去特定日期,

预期产出

Date       vtid        count   vtid1   count1  vtid2  count2
-------------------------------------------------------------
2013-05-07   7           4      null    null    null   null    
2013-05-08   7           5       8        3        9    1
2013-05-09   7           3       null    null    null   null  
2013-05-12   8           1       null    null    null   null

如果有人知道该怎么做请帮帮我....

2 个答案:

答案 0 :(得分:0)

这可能不像您希望的那样动态,但它会产生类似于vtid 7,8和9的预期输出的东西。

select d.Date, v7.vtid, v7.Count, v8.vtid, v8.Count, v9.vtid, v9.Count
from (select distinct convert(date,dtime) as Date from Transaction_tbl) as d
  left outer join (select convert(date,dtime) as Date, vtid, count(vtid) as Count from Transaction_tbl where vtid = 7 group by convert(date,dtime), vtid) as v7 on v7.Date = d.Date
  left outer join (select convert(date,dtime) as Date, vtid, count(vtid) as Count from Transaction_tbl where vtid = 8 group by convert(date,dtime), vtid) as v8 on v8.Date = d.Date
  left outer join (select convert(date,dtime) as Date, vtid, count(vtid) as Count from Transaction_tbl where vtid = 9 group by convert(date,dtime), vtid) as v9 on v9.Date = d.Date
order by d.Date

完全披露:我没有尝试过这个,可能会有一个拼写错误

编辑虽然这可能无法以适合您的格式生成输出,但数据透视查询更清晰,更容易修改

select *
from (
  select vtid, convert(date, create_date) as Date
  from Transaction_tbl
  where locid = 5
) as vt
pivot (
  count(vtid)
  for vtid in ([7], [8], [9])
) as pvt

答案 1 :(得分:0)

您真正需要的是具有动态列的PIVOT查询。这里有几个答案,显示了这方面的例子。请查看thisthisgoogle it。你从你想要的结果集中获得的差异类似于以下(数字可能略有不同,因为我只是粗略地看了一下上面的表,但你会得到这个想法);

Date       vtid-7     vtid-8      vtid-9   
2013-05-07   4           null      null
2013-05-08   5           3         1
2013-05-09   3           null      null
2013-05-12   null        1         null
2013-05-13   null        1         null
2013-05-15   1           null      1