Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Server - Conditional Grouping??? Need Help!

Status
Not open for further replies.

heatherb0123

Technical User
Dec 15, 2010
10
US
I am creating stored procedure in SQL Server 2008. I'm a little confused on how to group a specific column only when it meets the criteria below. Can anyone help? I have notes in the code below. Thanks.

Criteria:
1) @Coverage & @GroupByMain are optional i.e if a null value is passed for these parameters, they must be ignored
2) If @GroupByMain is not null then the column CalculatedSDCash should be grouped by HiNetMajor
------------------------------------------------------------------
Code:
CREATE PROCEDURE [dbo].[Sel_DCF_AcctCurrStatusHistory]
	@AsOfDate datetime,
	@Coverage nvarchar(20),
	@GroupByMain nvarchar(4)  --Will either be 'MAIN' or NULL
AS
BEGIN
SET NOCOUNT ON;

SELECT *    
FROM tblDCF_AcctCurrStatusHistory
WHERE ((@Coverage IS NULL) OR (Coverage = @Coverage))-- AND
--((@GroupByMain IS NULL) OR (@GroupByMain IS NOT NULL AND **Don't know what to do here** ))
GROUP BY 
--Not sure how I group "CalculatedSDCash" by "HiNetMajor" only if "GroupByMain" is not null??? And do I sum "CalculatedSDCash"?
END

Heather B...
 
Here's how I would do it. Just a guess, but you might also want to add criteria for your @AsOfDate parameter too?

Code:
CREATE PROCEDURE [dbo].[Sel_DCF_AcctCurrStatusHistory]
    @AsOfDate datetime,
    @Coverage nvarchar(20),
    @GroupByMain nvarchar(4)  --Will either be 'MAIN' or NULL
AS
BEGIN
SET NOCOUNT ON;


IF @GroupByMain IS NULL
	BEGIN
		SELECT *    
		FROM tblDCF_AcctCurrStatusHistory
		WHERE ((@Coverage IS NULL) OR (Coverage = @Coverage))
	END

	IF @GroupByMain = 'MAIN'
		BEGIN
			SELECT HiNetMajor, SUM(CalculatedSDCash) AS CalculatedSDCash
			FROM tblDCF_AcctCurrStatusHistory
			WHERE ((@Coverage IS NULL) OR (Coverage = @Coverage))
			GROUP BY HiNetMajor
	END

END
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top