如何转换此表:
+---------------------+-------------------------------+-------+-------+
| PropertyName | Emergency | Count | Total |
+---------------------+-------------------------------+-------+-------+
| IH | No | 8 | 12 |
| IH | No Water | 1 | 12 |
| IH | Smoke Alarm not working | 1 | 12 |
| IH | Broken Lock - Exterior | 1 | 12 |
| IH | Leaking Water | 1 | 12 |
| GG | No | 5 | 10 |
| GG | Leaking Water | 3 | 10 |
| GG | Property Damage (Significant) | 1 | 10 |
| GG | Toilet - Clogged (1 Bathroom) | 1 | 10 |
| PLB | No | 5 | 10 |
| PLB | Resident Locked Out | 2 | 10 |
| PLB | Smoke Alarm not working | 1 | 10 |
| PLB | Tub - Clogged (1 Bathroom) | 1 | 10 |
| PLB | Leaking Water | 1 | 10 |
+---------------------+-------------------------------+-------+-------+
像这样:
+---------------------+-------------------------------+-------+-------+
| PropertyName | Emergency | Count | Total |
+---------------------+-------------------------------+-------+-------+
| IH | No | 8 | 12 |
| | No Water | 1 | |
| | Smoke Alarm not working | 1 | |
| | Broken Lock - Exterior | 1 | |
| | Leaking Water | 1 | |
| GG | No | 5 | 10 |
| | Leaking Water | 3 | |
| | Property Damage (Significant) | 1 | |
| | Toilet - Clogged (1 Bathroom) | 1 | |
| PLB | No | 5 | 10 |
| | Resident Locked Out | 2 | |
| | Smoke Alarm not working | 1 | |
| | Tub - Clogged (1 Bathroom) | 1 | |
| | Leaking Water | 1 | |
+---------------------+-------------------------------+-------+-------+
我想做的是,如果PropertyName与上一行的下一行相同,则应该省略。对于总计应该是相同的。
我无法尝试LAG/LEAD
,因为我们仅使用SQL SERVER 2008
-我知道这简直太可笑了。
答案 0 :(得分:2)
您可以在CTE表达式中生成行号,然后按PropertyName
选择最上面的行号:
;with tableWithRowNums as(
select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum,
PropertyName,
Emergency,
Count,
Total
from the_table ),
first_rows as (
select min(rownum) as first_row,
PropertyName
from tableWithRowNums
group by rowNums.PropertyName
)
select ISNULL(first_rows.PropertyName, ''),
tableWithRowNums.Emergency,
tableWithRowNums.Count,
tableWithRowNums.Total
from tableWithRowNums
left join first_rows on first_rows.first_row = tableWithRowNums.rownum
order by tableWithRowNums.rownum;
答案 1 :(得分:0)
通常,最好在应用程序级别完成此操作。但是,在您的情况下,您似乎只是想要“否”行上的值。您可以使用一些case
表达式来完成此操作:
select (case when Emergency = 'No' then PropertyName end) as PropertyName,
Emergency, Count,
(case when Emergency = 'No' then Total end) as total
from t
order by max(total) over (partition by PropertyName) desc, -- you seem to want the largest total first
t.PropertyName,
(case when Emergency = 'No' then 1 else 2 end),
t.Total desc;
ORDER BY
非常重要。除非最外面的SELECT
有一个ORDER BY
,否则不能保证SQL查询以任何特定的顺序返回结果。