简体   繁体   中英

Two results from a stored procedure in MS SQL server 2008 R2

I have a stored procedure

CREATE PROCEDURE [dbo].[Sp_getdistrictreport] 
  -- Add the parameters for the stored procedure here 
  @DistrictName NVARCHAR(50) 
AS 
  BEGIN 
      -- SET NOCOUNT ON added to prevent extra result sets from 
      -- interfering with SELECT statements. 
      SET nocount ON; 

  -- Insert statements for procedure here 
  SELECT a.talukname, 
         Count (DISTINCT b.globalid) AS Samples_Collected 
  FROM   dbo.village a WITH (INDEX ([S22_idx])) 
         INNER JOIN dbo.gridpoint_1 b 
                 ON a.shape.Stintersects(b.shape) = 1 
         INNER JOIN dbo.gridpoint_1__attach c 
                 ON b.globalid = c.rel_globalid 
  WHERE  districtname = @DistrictName 
  GROUP  BY a.talukname 
END 

which will result

 TalukName               Samples_Collected
Heggadadevankote        |   1
Hunsur                  |   6
Krishnarajanagara       |   4
Mysore                  |   4
Tirumakudal - Narsipur  |   1

But I want to add one more column to this result (Total_SAMPLE), which gets the data from 1st INNER JOIN with the STintersect result. Please help me in modifying the stored procedure.

I got the answer.But it is taking 7.05 minutes for the result.Can anybody help to improve execution time or by any alternative method.

PROCEDURE [dbo].[sp_GetDistrictReportForDashboard]
    -- Add the parameters for the stored procedure here
    @DistrictName nvarchar(50)
AS
BEGIN

SET NOCOUNT ON;

SELECT samples_collected.talukname,sample_count,TotalSamples from 
(
SELECT a.TalukName talukname, COUNT (DISTINCT b.GlobalID) sample_count
FROM dbo.VILLAGE a WITH (INDEX ([S22_idx])) , DBO.GRIDPOINT_1 b , dbo.GRIDPOINT_1__ATTACH c
WHERE  a.SHAPE.STIntersects(b.Shape)=1
and b.GlobalID=c.REL_GLOBALID
and  a.DistrictName=@DistrictName
GROUP BY a.TalukName
) samples_collected,
(
SELECT a.TalukName talukname,COUNT (DISTINCT b.GlobalID) TotalSamples
FROM dbo.VILLAGE a
INNER JOIN
dbo.GRIDPOINT_1 b WITH (INDEX ([S26_idx])) ON a.SHAPE.STIntersects(b.Shape)=1 
WHERE a.DistrictName=@DistrictName
GROUP BY a.TalukName
) total
WHERE samples_collected.talukname=total.talukname

END

Result

talukname                    sample_count   TotalSamples
Heggadadevankote           |        1    |     55001
Hunsur                     |        6    |     31316
Krishnarajanagara          |        4    |     34297
Mysore                     |        4    |     18168
Tirumakudal - Narsipur     |        1    |     38668

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM