0

我有这样的查询

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

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

4

2 回答 2

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
于 2013-06-18T07:36:42.187 回答
0

您真正需要的是带有动态列的 PIVOT 查询。SO上有几个答案显示了这方面的例子。看看这个,或者这个,或者只是谷歌它。您将从所需结果集中获得的差异类似于以下内容(数字可能略有不同,因为我只是粗略地看了一眼上面的表格,但您会明白的);

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
于 2013-06-18T08:10:35.057 回答