【发布时间】:2021-10-14 14:57:45
【问题描述】:
这是我现在的代码。输出表中有 4 行,我想知道如何在表底部显示总计行。由于 DESC 的顺序,它目前显示在顶部。
USE [MyData]
SELECT * INTO tableOne FROM [DataLib].[dbo].[Lease] -- carry over Lease table from Data Library to Reporting Database
--populate new table with the 3 commerical sectors and their uniqu
CREATE TABLE commercial_expirations (
UniqueID varchar(255),
PropertyType varchar(50))
INSERT INTO commercial_expirations
VALUES ('Asset / Most Recent Quarter / All Assets / Sector | Industrial','Industrial'),
('Asset / Most Recent Quarter / All Assets / Sector | Office','Office'),
('Asset / Most Recent Quarter / All Assets / Sector | Retail','Retail'),
('Asset / Most Recent Quarter / All Assets / SectorType | Commercial','Total')
SELECT c.PropertyType AS 'Property Type',
e.SpaceArea_End AS 'RentableSF',
FORMAT(e.LsDuration_WAvg, 'N1') AS 'WA Duration (Yrs)',
FORMAT(e.[LsArea%_End], 'P1') AS '%Leased',
FORMAT(e.[Year0ExpireArea%], 'P1') AS '2021',
FORMAT(e.[Year1ExpireArea%], 'P1') AS '2022',
FORMAT(e.[Year2ExpireArea%], 'P1') AS '2023',
FORMAT(e.[Year3ExpireArea%], 'P1') AS '2024',
FORMAT(e.[Year4ExpireArea%], 'P1') AS '2025',
FORMAT(iif(e.[Year5ExpireArea%] IS NULL, 0, e.[Year5ExpireArea%]) + iif(e.[Year6ExpireArea%] IS NULL, 0, e.[Year6ExpireArea%]) + iif(e.[Year7ExpireArea%] IS NULL, 0, e.[Year7ExpireArea%]) + iif(e.[Year8ExpireArea%] IS NULL, 0, e.[Year8ExpireArea%]) + iif(e.[Year9ExpireArea%] IS NULL, 0, e.[Year9ExpireArea%]) + iif(e.[Year10ExpireArea%] IS NULL, 0, e.[Year10ExpireArea%]) + iif(e.[Year11PlusExpireArea%] IS NULL, 0, e.[Year11PlusExpireArea%]), 'P1') AS 'Thereafter'
INTO ##Schedule
FROM commercial_expirations AS c
LEFT JOIN tableOne AS e
ON c.UniqueID = e.RecordID;
SELECT [Property Type],
FORMAT(RentableSF, 'N0') AS 'Rentable SF',
[WA Duration (Yrs)],
[2021],
[2022],
[2023],
[2024],
[2025],
Thereafter
FROM ##Schedule
ORDER BY [RentableSF] DESC;
/*
DROP TABLE commercial_expirations
DROP TABLE expSummary
DROP TABLE ##Schedule
*/
【问题讨论】:
-
order by case when... -
在 ORDER BY 子句中添加
case [Property Type] when 'Total' then 1 else 0 end作为第一个条件。 -
@stu 如果我要使用它,不包括名称为总的行的语法是什么?
-
为什么需要所有这些临时表?为什么不只是一个查询?
-
INTO ##Schedule为什么这里需要一个全局临时表?是为了保证两个人不能同时运行这个查询吗?##global的真实用例很少,我建议坚持使用#local。
标签: sql-server ssms