[英]how to simplify the selection query
I have to selection queries like below in a stored procedure. 我必须在存储过程中选择以下查询。
SELECT @licenseCount = COUNT(*) FROM ServicePool SP
INNER JOIN UserPackages UP ON UP.ServicePoolId = SP.Id
AND SP.UserId = UP.UserId
INNER JOIN Package P ON P.Id = UP.PackageId
LEFT OUTER JOIN CompanyProfile C ON C.LicenseId = SP.Id
INNER JOIN CompanyProfile CP ON CP.CurrencyId = P.CurrencyId
INNER JOIN PackageCategory PC ON PC.OrganizationTypeId = CP.OrganisationType
AND PC.PackageId = P.Id
WHERE SP.Active = 1
AND SP.UserId = @uId
AND P.Active = 1
and CP.CompanyID = @cId
and ISNULL(C.CompanyID,0) = 0
AND DATEDIFF(DAY,GETDATE(),DATEADD(DAY,P.ValidityPeriod,UP.PurchaseDate)) > 0
SELECT @paymentCount = COUNT(*) FROM ServicePool SP
INNER JOIN UserPackages UP ON UP.ServicePoolId=SP.Id
AND SP.UserId = UP.UserId
INNER JOIN Package P ON P.Id = UP.PackageId
LEFT OUTER JOIN CompanyProfile C ON C.LicenseId = SP.Id
INNER JOIN CompanyProfile CP ON CP.CurrencyId = P.CurrencyId
INNER JOIN PackageCategory PC ON PC.OrganizationTypeId = CP.OrganisationType
AND PC.PackageId = P.Id
WHERE SP.Active = 1
AND SP.UserId = @uId
AND P.Active = 1
and CP.CompanyID = @cId
and ISNULL(C.CompanyID,0) = 0
AND DATEDIFF(DAY,GETDATE(),DATEADD(DAY,P.ValidityPeriod,UP.PurchaseDate)) > 0
AND UP.PaymentStatus = 'P'
As you can see, the only difference between the above two selection queries is that, at the end of second one, there is an extra where condition, AND UP.PaymentStatus = 'P'
. 如您所见,以上两个选择查询之间的唯一区别是,在第二个选择查询的末尾,还有一个额外的where条件,
AND UP.PaymentStatus = 'P'
。
So I was wondering is there any way I can simplify this queries? 所以我想知道有什么方法可以简化此查询吗?
Below would be the query 下面是查询
SELECT @licenseCount = COUNT(*), @paymentCount = COUNT(case when UP.PaymentStatus = 'P' then 1 else 0 end) FROM ServicePool SP
INNER JOIN UserPackages UP ON UP.ServicePoolId = SP.Id
AND SP.UserId = UP.UserId
INNER JOIN Package P ON P.Id = UP.PackageId
LEFT OUTER JOIN CompanyProfile C ON C.LicenseId = SP.Id
INNER JOIN CompanyProfile CP ON CP.CurrencyId = P.CurrencyId
INNER JOIN PackageCategory PC ON PC.OrganizationTypeId = CP.OrganisationType
AND PC.PackageId = P.Id
WHERE SP.Active = 1
AND SP.UserId = @uId
AND P.Active = 1
and CP.CompanyID = @cId
and ISNULL(C.CompanyID,0) = 0
AND
DATEDIFF(DAY,GETDATE(),DATEADD(DAY,P.ValidityPeriod,UP.PurchaseDate))
You can define @paymentCount variable in the first query itself 您可以在第一个查询本身中定义@paymentCount变量
Test Results - 检测结果 -
hive> select * from test_so_t1;
OK
123 90001 90001
123 90001 90002
123 90001 90003
123 90002 90001
123 90002 90002
123 90003 90002
123 90003 90003
Time taken: 0.118 seconds, Fetched: 7 row(s)
hive> select count(case when mem_id=90001 then 1 else 0 end) as groupBy, group_id from test_so_t1 group by group_id;
Total MapReduce CPU Time Spent: 3 seconds 900 msec
OK
7 123
Time taken: 17.271 seconds, Fetched: 1 row(s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.