码迷,mamicode.com
首页 > 数据库 > 详细

SQL窗口函數一例

时间:2014-09-30 03:14:32      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   os   使用   ar   文件   sp   

需求:

         MSSQL,列出服務實例中所有數據庫的如下信息: 數據庫ID、數據庫名、創建日期、數據文件類型、數據文件大小、數據庫總大小、文件所在路徑。


寫法(後面的百分比為所花時間占比):

-- 连接子查询  (47%)
WITH cte_TotalSize AS
(
	SELECT database_id
	      ,CAST(SUM(size) AS FLOAT)/128 AS [TotalSize(MB)]
	FROM sys.master_files
	GROUP BY database_id
)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,c.[TotalSize(MB)]
      ,a.physical_Name AS File_Path
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id
INNER JOIN cte_TotalSize c ON a.database_id = c.database_id


-- 标题子查询  (34%)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,(SELECT CAST(SUM(size) AS FLOAT)/128 FROM sys.master_files WHERE database_id = a.database_id) AS [TotalSize(MB)]
      ,a.physical_Name AS File_Path 
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id


-- 窗口函数  (19%)
SELECT a.database_id AS [DB_ID]
      ,b.name AS [DB_Name]
      ,b.create_date
      ,CASE a.type WHEN 1 THEN 'Log' ELSE 'Data' END AS File_Type
      ,CAST(a.size AS FLOAT)/128 AS [Size(MB)]  -- Size以页(8 KB)为单位
      ,CAST(SUM(size) OVER(PARTITION BY a.database_id) AS FLOAT)/128 AS [TotalSize(MB)]
      ,a.physical_Name AS File_Path 
FROM sys.master_files a
INNER JOIN sys.databases b ON a.database_id = b.database_id

結果:

bubuko.com,布布扣

均得出正確結果的上面三種方法,代碼越來越少,性能卻越來越好。。

其中第三種是使用了窗口函數,相關文檔:http://msdn.microsoft.com/zh-cn/library/ms189461.aspx


SQL窗口函數一例

标签:style   blog   http   io   os   使用   ar   文件   sp   

原文地址:http://blog.csdn.net/helloword4217/article/details/39680757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!