Wednesday, January 28, 2009

Tuesday, January 27, 2009

MYSQL - query to find top 10 favourite locations in each city

Here's a short example of using MYSQL CASE WHEN Control flow function alongwith User defined variables


SELECT CITY,Location,Most_Popular
FROM
(
SELECT @CITY,
CASE
WHEN (@CITY=CITYNAME FIELD AND @ROWNUM < 10) THEN (@ROWNUM:=@ROWNUM+1)
WHEN (@CITY != CITYNAME FIELD) THEN @ROWNUM:=1
ELSE @ROWNUM:=10
END AS CHANGED_CITY, @CITY:=CITYNAME FIELD, D.*
FROM (SELECT @ROWNUM:=0) R, (SELECT @CITY:='0') M,
(
SELECT CITY, Location, count(UserId Field) as Most_Popular
FROM Table Names
WHERE
Field Constraints
group by CITY,Location
order by CITY,Most_Popular Desc
)D
)D1
GROUP BY CITY,CHANGED_CITY
order by CITY,Most_Popular Desc;

Thanks to Ankit for helping me out on this...

Creative Commons License

Friday, January 23, 2009

MYSQL CASE WHEN EXAMPLE

Here's a short example of using CASE WHEN control flow statement for grouping users who write reviews by age group:

select CASE
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 15 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 25) THEN '15-25'
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 25 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 35) THEN '25-35'
WHEN ( FLOOR(datediff(CURRENT_DATE,DOB)/365) > 35 AND FLOOR(datediff(CURRENT_DATE,DOB)/365) < 50) THEN '35-50'
ELSE 'Above 50'
END as Age_Group,
count(*) as Reviews
FROM
Table names
WHERE
Field Constraints
group by Age_Group;

NOTE:
DOB:Date of Birth field



Creative Commons License

Dear Readers

Finally a blog to pen down my daily coding work...!! I have been thinking of setting up a blog for quite a long time where in i could write just about anything new that i keep learning about LAMP Stack and of course!! to keep a track of my coding tricks.....Keep watching this space for more posts...


Creative Commons License