我有这样的查询
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
如果有人知道该怎么做请帮帮我....
答案 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)