早上好,关于使用SQL创建报告的问题。花了一些时间试图弄清楚如何做到这一点。所以这是代码......
select
c.searchname as 'Client Name',
w.Date as 'Date',
j.Name as 'Engagement Name',
j.JobID as 'Eng #',
sum(units) as 'Hours',
ca.Description as 'Description'
from tblWip w
join tblJob j on w.jobid=j.jobid
join tblclient c on j.clientid=c.clientid
join tblChargeAccs ca on w.chargeacid=ca.ChargeAcID
where j.PartnerID='19'
group by c.searchname, j.name, w.date, j.jobid, w.units, w.amount, ca.description
order by c.searchname, w.date asc
哪个输出...
我想将输出格式化为更像......
有关如何重新排列这些列和行的任何建议吗?任何帮助表示赞赏。谢谢你的阅读!
答案 0 :(得分:1)
列的排序与SQL中Select子句中指定的完全相同。 这些行按照您在Order By Clause中指定的顺序排序。
所以要改变这些,只需改变你写这两个条款的方式:
select c.searchname 'Client Name',
j.Name 'Engagement Name',
j.JobID 'Eng #',
sum(units) hours,
from tblWip w
join tblJob j on w.jobid=j.jobid
join tblclient c on j.clientid=c.clientid
join tblChargeAccs ca on w.chargeacid=ca.ChargeAcID
where j.PartnerID='19'
group by c.searchname, j.name, w.date,
j.jobid, w.units, w.amount, ca.description
order by c.searchname, w.date asc
让列反映日期并为数据中的每个日期创建单独的列更难。这称为Pivot数据。谷歌这是它自己的话题。大多数数据库产品都有内置函数(在SQL Server中称为Pivot),它将为您执行此操作,但您需要阅读文档(提供一个链接)以了解如何正确使用它。
如果您提前知道哪些日期需要列,则可以在没有动态透视的情况下编写它。使用您的示例数据:
select c.searchname 'Client Name',
j.Name 'Engagement Name',
j.JobID 'Eng #',
sum(case when w.Date = '25Jun2017' then units end) '25Jun2017hours',
sum(case when w.Date = '26Jun2017' then units end) '26Jun2017hours',
sum(case when w.Date = '27Jun2017' then units end) '27Jun2017hours'
from tblWip w
join tblJob j on w.jobid=j.jobid
join tblclient c on j.clientid=c.clientid
join tblChargeAccs ca on w.chargeacid=ca.ChargeAcID
where j.PartnerID='19'
group by c.searchname, j.name, w.date,
j.jobid, w.units, w.amount, ca.description
order by c.searchname, w.date asc