我有一個查詢涉及SQL Server中的2個表'Coupons'和'CouponUsedLog',下面的查詢將從這2個表中獲得一些信息供統計學研究使用。不知爲什麼,我覺得儘管我的查詢能夠正常工作,並將結果返回給我,但我覺得我可以用更高效的方式編寫,如果有更好的方法來重寫,有人可以請教一下嗎?我是否使用了太多不必要的變量和連接?謝謝。SQL查詢+更高效的替代
DECLARE @CouponISSUED int=null
DECLARE @CouponUSED int=null
DECLARE @CouponAVAILABLE int=null
DECLARE @CouponEXPIRED int=null
DECLARE @CouponLastUsed Date=null
--Total CouponIssued
SET @CouponISSUED =
(
select count(*)
from Coupon C Left Join
couponusedlog CU on C.autoid = CU.Coupon_AutoID
where C.VoidedBy is null and
C.VoidedOn is null and
DeletedBy is null and
DeletedOn is null and
Card_AutoID in (Select AutoID
from Card
where MemberID = 'Mem001')
)
--Total CouponUsed
SET @CouponUSED =
(
select count(*)
from couponusedlog CU Left Join
Coupon C on CU.Coupon_AutoID = V.autoid
where CU.VoidedBy is null and
CU.VoidedOn is null and
C.Card_AutoID in (select AutoID
from Card
where MemberID = 'Mem001')
)
SET @CouponAVAILABLE = @CouponISSUED - @CouponUSED
--Expired Coupons
SET @CouponEXPIRED =
(
select Count(*)
from Coupon C Left Join
couponusedlog CU on C.autoid = CU.Coupon_AutoID
where C.VoidedBy is null and
C.VoidedOn is null and
deletedBy is null and
deletedOn is null and
Card_AutoID in (select AutoID
from Card
where MemberID = 'Mem002') and
CONVERT (date, getdate()) > C.expirydate
)
--Last Used On
SET @CouponLastUsed =
(
select CONVERT(varchar(10),
Max(VU.AddedOn), 103) AS [DD/MM/YYYY]
from couponusedlog CU Left Join
coupon C on CU.Coupon_AutoID = C.autoid
where CU.voidedBy is null and
CU.voidedOn is null and
C.Card_AutoID in (select AutoID
from Card
where MemberID = 'Mem002')
)
Select @CouponISSUED As Coupon_Issued,
@CouponUSED As Coupon_Used,
@CouponAVAILABLE As Coupon_Available,
@CouponEXPIRED As Coupon_Expired,
@CouponLastUsed As Last_Coupon_UsedOn
是的,這是針對SQL Server的。 – k80sg