Brad
Brad

Reputation: 635

Grouping Query Help in SQL Server

I am trying to sort my data by certain groups of people. My Data Looks Like:

Origional_Date  ID      FORM    Total
2012-03-01      1855    3       1283
2012-03-01      2869    4       2306
2012-03-01      5555    4       6440
2012-03-01      5555    3       8373
2012-03-01      2527    3       8476
2012-03-01      922     3       823
2012-03-15      2907    4       1420
2012-03-15      5555    3       2892
2012-03-15      2914    4       5008
2012-03-15      2375    3       4594

The Query I have so far is:

DECLARE @StartDate smalldatetime, @EndDate smalldatetime, @Web_ID as smallint
    SET @StartDate = '20120301'
    SET @EndDate = '20120331'
    SET @Web_ID = '5555'

SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1) as [Origional_Date]
  ,[ID]
  ,[Form]
  ,SUM([Total]) as [Total]
  FROM mytable
  WHERE [Origional_Date] between @StartDate and @EndDate
    AND [ID] = @Web_ID
  GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1), [ID], [Form]
  ORDER BY [Origional_Date], [Form] ASC

What I am trying to do is display my data like:

Origional_Date  ID      FORM    Total
2012-03-01      Web     3       8373
2012-03-01      Direct  3       10582
2012-03-01      Web     4       6440
2012-03-01      Direct  4       2306
2012-03-15      WEB     3       2892
2012-03-15      Direct  3       4594
2012-03-15      Direct  4       6428

Where Web is ID 5555 and Direct is anything else.

I am just not sure how if this can be done with an "IF" statement or if it needs to be done in the "group by"

THANK YOU!

Upvotes: 1

Views: 52

Answers (2)

Jones
Jones

Reputation: 1500

Using Case clausule

select case active
    when 1 then 'Active'
    when 0 then 'Inactive'
    end         
from contract

in your case is similar of this:

select case [ID]
    when 5555 then 'Web'
    else 'Direct'
    end as [ID]
from mytable

Upvotes: 1

hkutluay
hkutluay

Reputation: 6944

You can use case statement to achieve this.

like

SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1) as [Origional_Date]
  ,(CASE WHEN [ID] = 5555 THEN 'Web' ELSE 'Direct' END )
  ,[Form]
  ,SUM([Total]) as [Total]
  FROM mytable
  WHERE [Origional_Date] between @StartDate and @EndDate
    AND [ID] = @Web_ID
  GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1), (CASE WHEN [ID] = 5555 THEN 'Web' ELSE 'Direct' END ), [Form]
  ORDER BY [Origional_Date], [Form] ASC

Upvotes: 1

Related Questions