I have a query where I generate our monthly customer contact activity. We have several categories (email out, email in, phone call in, phone call out, etc.) There are 8 distinct "type" results. I need to have two groups-one for all "email" and one for all "phone". Currently, I have a WHERE TYPE LIKE '%Email%'and TYPE LIKE '%Call%'. However, I am not able to group by these two "LIKE" statements. Does anyone know how I can best achieve this?
I simplified the query down to this for the example:
SELECT TYPE
FROM dbo.HISTORY
WHERE (TYPE LIKE '%email%') OR
(TYPE LIKE '%call%')
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
Unfortunately, you have a badly structured database, having combined SUBJECT and TERM into the same column. When you use GROUP BY it treats each unique value in the column as a group in the result set.
The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group.
GROUP BY Clause is utilized with the SELECT statement. GROUP BY aggregates the results on the basis of selected column: COUNT, MAX, MIN, SUM, AVG, etc. GROUP BY returns only one result per group of data. GROUP BY Clause always follows the WHERE Clause.
This should work:
SELECT
TYPE
FROM
dbo.HISTORY
WHERE
(TYPE LIKE '%email%') OR (TYPE LIKE '%call%')
GROUP BY
CASE
WHEN type LIKE '%email%' THEN 'email'
WHEN type LIKE '%call%' THEN 'call'
ELSE NULL
END
Although, my advice would be to have a type code table with another column that tells whether each type is considered an email or call. Then you're not reliant on the type name following a specific format which is sure to be forgotten down the road. You can then easily group on that:
SELECT
H.type
FROM
dbo.History
INNER JOIN dbo.History_Types HT ON
HT.history_type_code = H.history_type_code AND
HT.history_type_category IN ('Email', 'Call')
GROUP BY
HT.history_type_category
SELECT H.type FROM dbo.History INNER JOIN dbo.History_Types HT ON HT.history_type_code = H.history_type_code AND HT.history_type_category IN ('Email', 'Call') GROUP BY HT.history_type_category
Wouldn't it be better to put the filter statement into the where clause?
SELECT
H.type FROM
dbo.History
INNER JOIN dbo.History_Types HT ON
HT.history_type_code = H.history_type_code
WHERE **HT.history_type_category IN ('Email', 'Call')**
GROUP BY HT.history_type_category
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With