Solved

SQL-- count and if statement

Posted on 2015-01-31
3
145 Views
Last Modified: 2015-02-03
There are 3 fields in the attached:
Rating, Color, Color_Type.  

If I run the following code against the table, it returns the 3 records that contain 'blue'  (blue, light blue, dark blue).

Select Rating, Color, Color_Type
from Table
where Color like ('%blue%')

I need to add a condition that does a count on the total # of records, and adds an "if" condition.  The condition is:
if there are < 3 records in the output, remove the "where color like " clause & show the entire output.  In the full list of colors, sort that color to the top.  

else if there are 3 or greater records with the specified color (3+ records in the output), show just those records.  The SQL for this condition is simply the original SQL:
Select Rating, Color, Color_Type
from Table
where Color like ('%blue%')

For example, for color like ('%blue%'), it would just return the 3 blue records.

But for yellow, since there's only 1 yellow record, it would return all 27 records, with yellow sorted to the top.



Ranking      Color      Color_type
83      Blue      Regular
46      Black      Regular
34      Brown      Regular
45      Gray      Regular
34      Dark Blue      Dark
67      Light Blue      Light
85      Dark Brown      Dark
98      Light Brown      Light
45      Dark Gray      Dark
36      Light Gray      Light
27      Silver      Regular
75      Dark Silver      Dark
56      Light Silver      Light
75      Beige      Light
55      Yellow      Regular
66      White      Light
78      Red      Regular
34      Green      Regular
24      Orange      Regular
2      Maroon      Regular
32      Purple      Regular
82      Dark Purple      Dark
32      Light Purple      Light
65      Dark red      Dark
36      Light Red      Light
75      Dark Orange      Dark
96      Light Orange      Light
If-SQL.xlsx
0
Comment
Question by:BBRRGG
3 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
I would put the sql into a stored proc
There i would define a table variable, and insert the results of the query with the filter into that table.
Then using a check on @@rowcount variable, decide if you want to add the other rows to that table also or not.
At the end rreturn the table results with the proper order by
Hope this helps already
0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 500 total points
Comment Utility
create table #table (
    rating int,
    color varchar(30),
    color_type varchar(30)
    )
insert into #table
        select '83' as rating,      'Blue' as color,      'Regular' as color_type union all select
        '46','Black','Regular' union all select
        '34','Brown','Regular' union all select
        '45','Gray','Regular' union all select
        '34','Dark Blue','Dark' union all select
        '67','Light Blue','Light' union all select
        '85','Dark Brown','Dark' union all select
        '98','Light Brown','Light' union all select
        '45','Dark Gray','Dark' union all select
        '36','Light Gray','Light' union all select
        '27','Silver','Regular' union all select
        '75','Dark Silver','Dark' union all select
        '56','Light Silver','Light' union all select
        '75','Beige','Light' union all select
        '55','Yellow','Regular' union all select
        '66','White','Light' union all select
        '78','Red','Regular' union all select
        '34','Green','Regular' union all select
        '24','Orange','Regular' union all select
        '2','Maroon','Regular' union all select
        '32','Purple','Regular' union all select
        '82','Dark Purple','Dark' union all select
        '32','Light Purple','Light' union all select
        '65','Dark red','Dark' union all select
        '36','Light Red','Light' union all select
        '75','Dark Orange','Dark' union all select
        '96','Light Orange','Light'


DECLARE @color varchar(30)
SET @color = '%blue%'

;WITH cteColorCount AS
(
    SELECT SUM(1) AS Color_Count
    FROM #table
    WHERE Color LIKE @color
)
SELECT Rating, Color, Color_Type
FROM #table
CROSS JOIN cteColorCount
WHERE
    Color LIKE CASE WHEN Color_Count < 3 THEN '%' ELSE @color END
ORDER BY
    CASE WHEN color LIKE @color THEN 1 ELSE 2 END

SET @color = '%yellow%'

;WITH cteColorCount AS
(
    SELECT SUM(1) AS Color_Count
    FROM #table
    WHERE Color LIKE @color
)
SELECT Rating, Color, Color_Type
FROM #table
CROSS JOIN cteColorCount
WHERE
    Color LIKE CASE WHEN Color_Count < 3 THEN '%' ELSE @color END
ORDER BY
    CASE WHEN color LIKE @color THEN 1 ELSE 2 END
0
 

Author Closing Comment

by:BBRRGG
Comment Utility
Great solution!
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now