SQL子类别总计未正确放置在每个父类别的末尾

时间:2018-08-16 16:43:50

标签: sql sql-server-2012

我在SQl查询中遇到问题,查询结果应该是这样

+------------+------------+-----+------+-------+--+--+--+
|  District  |   Tehsil   | yes |  no  | Total |  |  |  |
+------------+------------+-----+------+-------+--+--+--+
| ABBOTTABAD | ABBOTTABAD | 377 | 5927 |  6304 |  |  |  |
| ABBOTTABAD | HAVELIAN   | 112 | 2276 |  2388 |  |  |  |
| ABBOTTABAD | Overall    | 489 | 8203 |  8692 |  |  |  |
| CHARSADDA  | CHARSADDA  | 289 | 3762 |  4051 |  |  |  |
| CHARSADDA  | SHABQADAR  | 121 | 1376 |  1497 |  |  |  |
| CHARSADDA  | TANGI      |  94 | 1703 |  1797 |  |  |  |
| CHARSADDA  | Overall    | 504 | 6841 |  7345 |  |  |  |
+------------+------------+-----+------+-------+--+--+--+

应该在每个父类别的末尾显示overall总数,但现在这样显示

+------------+------------+-----+------+-------+--+--+--+
|  District  |   Tehsil   | yes |  no  | Total |  |  |  |
+------------+------------+-----+------+-------+--+--+--+
| ABBOTTABAD | ABBOTTABAD | 377 | 5927 |  6304 |  |  |  |
| ABBOTTABAD | HAVELIAN   | 112 | 2276 |  2388 |  |  |  |
| ABBOTTABAD | Overall    | 489 | 8203 |  8692 |  |  |  |
| CHARSADDA  | CHARSADDA  | 289 | 3762 |  4051 |  |  |  |
| CHARSADDA  | Overall    | 504 | 6841 |  7345 |  |  |  |
| CHARSADDA  | SHABQADAR  | 121 | 1376 |  1497 |  |  |  |
| CHARSADDA  | TANGI      |  94 | 1703 |  1797 |  |  |  |
+------------+------------+-----+------+-------+--+--+--+

我的查询正在相对于第一列对第二列进行排序,尽管按查询顺序应用于我的第一列。这是我的查询

select District as 'District', tName as 'tehsil',[1] as 'yes',[0] as 'no',ISNULL([1]+[0], 0) as "Total" from
(
select d.Name as 'District',
case when grouping (t.Name)=1 then 'Overall'  else t.Name end as tName,
BoundaryWallAvailable,
count(*) as total from School s 
INNER JOIN SchoolIndicator i ON (i.refSchoolID=s.SchoolID)
INNER JOIN Tehsil t ON (t.TehsilID=s.refTehsilID)
INNER JOIN district d ON (d.DistrictID=t.refDistrictID)
group by 
GROUPING sets((d.Name, BoundaryWallAvailable), (d.Name,t.Name, BoundaryWallAvailable))
) B
PIVOT
(
max(total)  for BoundaryWallAvailable in ([1],[0]) 
) as Pvt
order by District

P.S:BoundaryWall是通过枢轴旋转的一列,我将其分为YesNo

0 个答案:

没有答案