我是相對較新的SQL,我希望對此有所幫助。基本上,我試圖在查詢中做一些計算,因爲函數有點慢。你們能改進嗎?如何優化此T-SQL查詢?
-- Query to retrive ADA from every school
Select Distinct DY,
DATENAME(MM,DT) as 'Month',
CONVERT(nvarchar,DT,101) as 'Date',
(
Select ((@M_stu - (Select Count(SC) from dbo.ATT where sc=1 AND al!='' AND DY=T.DY))/@M_stu)*100
) as 'Merced ADA',
(
Select ((@A_stu - (Select Count(SC) from dbo.ATT where sc=2 AND al!='' AND DY=T.DY))/@A_stu)*100
) as 'Atwater ADA',
(
Select ((@L_stu - (Select Count(SC) from dbo.ATT where sc=3 AND al!='' AND DY=T.DY))/@L_stu)*100
) as 'Livingston ADA',
(
Select ((@B_stu - (Select Count(SC) from dbo.ATT where sc=4 AND al!='' AND DY=T.DY))/@B_stu)*100
) as 'Buhach ADA',
(
Select ((@Y_stu - (Select Count(SC) from dbo.ATT where sc=5 AND al!='' AND DY=T.DY))/@Y_stu)*100
) as 'Yosemite ADA',
(
Select ((@I_stu - (Select Count(SC) from dbo.ATT where sc=6 AND al!='' AND DY=T.DY))/@I_stu)*100
) as 'Independence ADA',
(
Select ((@G_stu - (Select Count(SC) from dbo.ATT where sc=10 AND al!='' AND DY=T.DY))/@G_stu)*100
) as 'Golden Valley ADA',
(
Select ((@S_stu - (Select Count(SC) from dbo.ATT where sc=92 AND al!='' AND DY=T.DY))/@S_stu)*100
) as 'Sequoia ADA'
From dbo.ATT as T
Order by DY ASC
刪除'Distinct'並添加'Group BY DY',您將(幾乎)擁有它。 – RBarryYoung
這很好。它絕對可以改善我的查詢。我決定把代碼放到一個View中來調用這個查詢,就好像它是一個普通的表一樣,但是現在我無法在查詢中保持常量(@M_stuct)。你知道這個方法嗎? – rne1223
@ me1223不,您不能在視圖中使用參數,但可以使用表函數。 http://stackoverflow.com/questions/1687279/can-we-pass-parameter-to-a-view-in-sql –