我必须在存储过程中选择如下所示的查询。
sklearn
如您所见,以上两个选择查询之间的唯一区别是,在第二个选择查询的末尾,还有一个额外的where条件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'
。
所以我想知道有什么方法可以简化此查询吗?
答案 0 :(得分:1)
下面将是查询
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))
您可以在第一个查询本身中定义@paymentCount变量
测试结果-
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)