Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
krisis
Starting Member
6 Posts |
Posted - 2005-02-03 : 22:46:44
|
| I wish to do a select query that grabs the count(data) from a table, and also grabs the data details from another table and links them together. Then order by the count. The problem is that I can't find the right query that will also return the rows whereby there is no matching data in the count table (i.e. count=0).i.e.table_COUNT has columns DATA, TIMEtable_INFO has columns DATA, USER, ORIGIN, CATEGORYI want to be able to SELECT * FROM table_INFO where data LIKE '%websitename%'and also to grab the count of how many times data is in table_COUNT, so:SELECT count(table_COUNT.data) FROM table_COUNT, table_INFO WHERE table_COUNT.data = table_INFO.dataand in the cases where there is no matching data in table_COUNT, to return a value of 0.So results I want would look something like:count, data, user, origin, category23, websitenameABC, john, 127.0.0.1, finance16, websitenameMND, fred, 127.0.0.1, health3, websitenameFFD, paul, 127.0.0.1, finance0, websitenameXYZ, peter, 127.0.0.1, computersHow can I do this? |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2005-02-03 : 22:51:51
|
MAybe something like:SELECT isnull(d.ct,0) [count], i.data, i.user, i.origin, i.categoryFROM table_INFO iLEFT OUTER JOIN ( SELECT data, count(data) ct FROM table_COUNT GROUP BY data) d ON d.data = i.dataWHERE i.data LIKE 'websitename%'ORDER BY isnull(d.ct,0) DESC |
 |
|
|
krisis
Starting Member
6 Posts |
Posted - 2005-02-03 : 23:00:46
|
| I get the error:Column 'table_COUNT.data' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. |
 |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2005-02-03 : 23:02:12
|
| Oops, I forgot the GROUP BY in the derived query. Copy the code again and try it again. |
 |
|
|
krisis
Starting Member
6 Posts |
Posted - 2005-02-03 : 23:05:53
|
| Works great!Thanks for the very prompt response. |
 |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2005-02-03 : 23:06:37
|
Your welcome |
 |
|
|
krisis
Starting Member
6 Posts |
Posted - 2005-03-21 : 00:02:22
|
| Is it also possible to return (in the same query) the TIME field from table_COUNT corresponding to the most recent datetime that DATA was entered?i.e. it should basically be the TIME result equal toSELECT TOP 1 time FROM table_COUNT WHERE data = 'datestuff' ORDER BY time DESC |
 |
|
|
|
|
|
|
|