在sql中将行-列结果转换为行

在sql中将行-列结果转换为行,sql,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 vtid1 count1 vtid2 coun

我有这样的疑问

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   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

如果有人知道怎么做,请帮助我……

这可能不像您希望的那样动态,但它将产生类似于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
完全披露:我没有试图运行这个,可能有一个输入错误

编辑:虽然这可能不会以适合您的格式生成输出,但pivot查询更简洁,更易于修改

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

您真正需要的是具有动态列的PIVOT查询。这里有几个答案,以展示这方面的例子。看看,或者只是看看。从期望的结果集中得到的差异如下所示(数字可能有点出入,因为我只是粗略地看了一下上面的表格,但你会明白的)


vtid是否有一个可变数量的值,或者它始终是7、8或9?vtid是一个可变数量,通常vtid是某个位置id。例如,如果我再添加一个操作,则新vtid将创建为10。如果vtid列的基数固定/较小,则可以使用单个sql查询执行此操作。否则,您需要使用我如何处理单个sql查询的过程,您能否显示我忘记了“on”子句,我没有理解您,我在sql server中运行此查询,,但我得到的错误是,列“Transaction_tbl.vtid”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。如果要将该查询另存为过程,只要内存正确,就可以在查询前加上“create proc MyProcName as”。然后可以使用“exec MyProcName”运行它。当然,MyProcName可以是任何您想要的。在上面的查询中,我必须再提供一个筛选“我想添加locid=5的位置”,那么我可以在哪里添加这个?
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
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