我尝试了以下查询来显示数据
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<table class="EventLogGrid" style="padding: 0px; ">
<tr>
<th>
Event Type
</th>
<th>
Event Description
</th>
<th>
Revision
</th>
<th>
Version
</th>
<th>
Log By
</th>
<th>
Log Date
</th>
<th>
Organization Name
</th>
<th>
Document Owner Organization
</th>
</tr>
@foreach (var item in Model.eventLogData)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EventType)
</td>
<td>
@item.EventDescription
</td>
<td>
@Html.DisplayFor(modelItem => item.Revision)
</td>
<td>
@Html.DisplayFor(modelItem => item.DocVersion)
</td>
<td>
@Html.DisplayFor(modelItem => item.LogBy)
</td>
<td>
@Html.DisplayFor(modelItem => item.LogDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.OrganizationName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DocumetOwnerOrganizationName)
</td>
</tr>
}
</table>
</body>
</html>
我得到的数据是这样的 -
select e.Name,ic.Code,t1.pyear,t1.pmonth,t2.Amount
from t1
inner join t2 on t2.id=t1.id
inner join t3 on t3.Code=t2.Code
inner join t4 e on t4.employeeindex=t1.employeeindex
where t1.pyear=2016 and t1.pmonth=1
union all
select e.Name,ic.Code,t1.pyear,t1.pmonth,t2.Amount
from t1
inner join t2 on t2.id=t1.id
inner join t3 on t3.Code=t2.Code
inner join t4 e on t4.employeeindex=t1.employeeindex
where t1.pyear=2016 and t1.pmonth=2
现在我想显示这样的数据
scode amount month year e_name
abc 3847 1 2016 john
ABC 20938 2 2016 john
XYZ 2838 1 2016 david
XYZ 29384 2 2016 david
任何解决方案?
答案 0 :(得分:1)
您可以尝试使用cte。以下只是一个例子,自己调整列名,因为它有点混乱
WITH unionall AS (
select ic.Code, t2.Amount, t1.pmonth, t1.pyear, e.Name
from t1
inner join t2 on t2.id=t1.id
inner join t3 on t3.Code=t2.Code
inner join t4 e on t4.employeeindex=t1.employeeindex
where t1.pyear=2016 and (t1.pmonth=1 OR t2.pmonth=2)
)
SELECT r1.scode, r1.amount as amount1, r2.amount as amount2
FROM unionall r1 inner join unionall r2 on r1.scode = r2.scode
如果您确定每个s_code有2个月(或至少是一个恒定数字),您可以轻松地自行连接并使用别名选择所有值,如下所示:
SELECT r1.scode, r1.amount as amount1, r2.amount as amount2 [...more fields...]
FROM result r1 inner join result r2 on r1.scode = r2.scode [...many joins as many months...]
如果你可能有多个月你不知道,我可能会在mysql上做group_concat。基本上,您按scode分组然后在同一个字段中有一个列表分隔值。太糟糕了,你不能在SQLServer中做group_concat,但是有网上的解决方法指南