Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MYSQL


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





ORDER Based On One Field But LIMIT Based On Another?


Say I have a table with students and their grades, and I want to get the students with the top 10 grades, but the result to be sorted based on their name. How would I do that?




View Complete Forum Thread with Replies

Related Forum Messages:
Change Value In Field Based On Order
I have a field that is an INT and can contain a value of 0 or greater. When the value is 0 it creates a unique situation and users of the site will sometimes change this to 0 on purpose because this value can have your item show up in the search results on the first page. Why, if a person orders the information ASC, it will show up first.

I have to allow this field to be 0, long story, but I want to "punish" them if this is so. Based on the type of search (ASC or DESC) as the user can pick. I want those items to always show up last.

Currently I am passing a variable that gets set via a form w/ that information, but I don't know how to check in the query how the variable is set. I was thinking CASE but I thought that only looks at a field in the db, not some variable that is being passed.

Either way, I hope this is making sense. Here is the query (pretty simple).

Code: ......

View Replies !
LIMIT Based On Unuiqe Values
i have a query where i search the table on the table using an alias (a in this case) and then find all rows for that user using the alias b, but now i need to limit the results to say 5 unique rows from table a but allowing any amount from table b, also table a may return multiple uids for one user

Code:

SELECT b.uid, b.field, b.value FROM user_s as a, user_s as b WHERE b.uid=a.uid <where clause for table a here> GROUP BY b.field, b.uid ORDER BY uid

View Replies !
Order Records Based On Two Columns
I'm working on PM feature for my site. So far I have this table:

+-----------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-----------+------+-----+---------+----------------+
| ID | int(11) | NO | PRI | NULL | auto_increment |
| subject | char(100) | YES | | NULL | |
| body | blob | YES | | NULL | |
| r_id | int(11) | YES | | NULL | |
| s_id | int(11) | YES | | NULL | |
| date_sent | int(11) | YES | | NULL | |
| date_read | int(11) | YES | | 0 | |
| r_date_to_trash | int(11) | YES | | NULL | |
| s_date_to_trash | int(11) | YES | | NULL | |
| r_status | int(11) | YES | | NULL | |
| s_status | int(11) | YES | | NULL | |
+-----------------+-----------+------+-----+---------+----------------+

r_id - "Receiver's ID"
s_id - "Sender's ID"
r_date_to_trash - "Unix timestamp when receiver deletes the message"
s_date_to_trash - "Unix timestamp when sender deletes the messages"
r_status - "receivers msg status, if r_status == 1 then message is in the trash
s_status - "senders msg status, if s_status == 1 then message is in the trash

So this is the query I have right now:
SELECT * FROM pm WHERE (r_id = 1 AND r_status = 1) OR (s_id = 1 AND s_status = 1)

This is the result:
+-----+------+------+-----------------+-----------------+----------+----------+
| ID | r_id | s_id | r_date_to_trash | s_date_to_trash | r_status | s_status |
+-----+------+------+-----------------+-----------------+----------+----------+
| 104 | 1 | 2 | 1226972079 | NULL | 1 | 0 |
| 110 | 1 | 2 | 1226971762 | NULL | 1 | 0 |
| 111 | 1 | 2 | 1226971891 | NULL | 1 | 0 |
| 112 | 1 | 2 | 1226972033 | NULL | 1 | 0 |
| 113 | 1 | 2 | 1226972462 | NULL | 1 | 0 |
| 120 | 2 | 1 | 0 | 1227103836 | 0 | 1 |
| 122 | 2 | 1 | 0 | 1227103841 | 0 | 1 |
| 127 | 2 | 1 | 1226972346 | 1226972090 | 1 | 1 |
| 128 | 2 | 1 | 0 | 1226972095 | 0 | 1 |
| 129 | 2 | 1 | 0 | 1226972176 | 0 | 1 |
| 130 | 2 | 1 | 0 | 1226972396 | 0 | 1 |
+-----+------+------+-----------------+-----------------+----------+----------+

This is the problem:
I'm trying to list the messages that are in the trash in order by date they were deleted (r_date_to_trash, s_date_to_trash). I need to join these two fields somehow together and then I could just do ORDER BY whatever DESC. That way the messages in the trash will show up in the order they are deleted.

View Replies !
Order By Based On Results From Another Table
I have a query that , and i need to order the result based on wheter or not the ID of my main table appears on another table, somewhat like this:

SELECT A.id AS Id, A.nome AS Nome
FROM main_table A
JOIN joined_table JT ON JT.id = A.id_cat
ORDER BY ("first whoever have a row in" another_table AT)

another_table stores the image paths related to main_table , i need to show all query results from main_table even if they don't have a image (row in another_table), but i need to show whoever have a image (a row in another_table) first...

I've tryied to join with another_table and even to use sobqueryes in ORDER B... but so far i got no results. it's even worst because this query is a monter with multiple lines (the sample is simplyfied...)

View Replies !
Adding A Key Field Based On Other Columns
I have a MYSQL db based on an excel sheet

There's a membership number field that's mostly empty, there's five different levels of membership from full to part time and so on, each represented by a 'Y' in the relevant field, also a date field with the date that they first joined

What I want to do is allocate a unique membership number for each member, a six figure number starting at 100001 upwards for the full members starting with the oldest memberships, 200001 upwards for the part time members, and so on.

View Replies !
Selecting Fields Based On The Value Of Another Field
My friend asked me to help with this query but unfortunately I wasn't able to figure it our for him. Here's the info he presented to me:

Table 1 - portrait
field 1 - id
field 2 - type (will be the id from a row in business or personal)

Table 2 - business
field 1 - id
field 2 - bizname

Table 3 - personal
field 1 - id
field 2 - firstname
field 3 - lastname

His PHP code will select a row from portrait where 'id' is a given number. Then based on the value of 'type' for that row he will either select the 'bizname' for that corresponding id or 'firstname' and 'lastname'. There is no way to know ahead of time whether the row is a business or personal account.

If this can be done without a subquery, that is ideal. However, if a subquery is required, that's ok, too.

View Replies !
Combining Multiple Records Into One Based On A Key Field
I'm really scratching my head over this one. I'm working with CSV data exported from Excel, which explains why it's a mess to begin with.

Within a table (or via any other means someone might be able to recommend) I need to combine multiple records which share two like fields. (If that's not clear, the real-world explanation is below.....

View Replies !
Selecting All Records Without Dups Based On One Field?
I have a table with 5 fields, of which several sometimes have
duplicates.

example;

| id | item | day | hour | ip_address |
| 1 | 3 | 2 | 11 | 204.156.33.78 |
| 2 | 7 | 2 | 15 | 122.165.177.211 |
| 3 | 1 | 3 | 1 | 205.52.79.122 |
| 4 | 7 | 3 | 9 | 122.165.177.211 |
| 5 | 11 | 3 | 9 | 177.15.99.111 |
| 6 | 24 | 3 | 17 | 122.165.177.211 |

As you can see the ip address may obviously have dupe entries (as do other fields but I don't care if they are dupes) and I want to query the table and get all the fields but only one where there is dupe ip_address 's.

So that I would get these results;

| id | item | day | hour | ip_address |
| 1 | 3 | 2 | 11 | 204.156.33.78 |
| 2 | 7 | 2 | 15 | 122.165.177.211 |
| 3 | 1 | 3 | 1 | 205.52.79.122 |
| 5 | 11 | 3 | 9 | 177.15.99.111 |

View Replies !
Detecting Duplicates Based On One Field In A Table?
I can't seem to find an answer anywhere for this as most people want to delete duplicate records.

I have a table, lots of fields, one of which is "title". I want mysql to return all the rows where "title" is the same. For instance if "title" was "Lord of the Rings" on id = 1 and id = 2, then the query would return both of the records, but ignore the others. It doesn't matter what the other field values are.

I have found some
SELECT COUNT( * ) AS num_entries, title
FROM title_table
WHERE title >1
GROUP BY title

But this doesn't seem to work, although looks like it's on the right sort of lines?

I'm not a Mysql expert, so my experience is mostly limited to the usual select, insert, update and delete queries!

View Replies !
Updating A Database Field Based On A String Or Filename
I am using MySQL to store images that I serve up with Coppermine photo gallery. Each image is shown in low resolution format. I also store medium and high resolution versions of these files for download. There is a caption field where I put these links using BBcode. It looks something like this: Code:

View Replies !
Trigger That Fills In A Missing Foreign Key Based On Another Field
To provide an easy insert methods for our client, I'm trying to write a trigger that fills in a missing foreign key based on another field that is inserted.

Basically, 'dr_market_id' is inserted and I'm trying to find 'market_id' by selecting the appropriate row in the markets table.
area_codes_markets.market_id is foreign key to markets.id

delimiter |

CREATE TRIGGER area_codes_markets_ins
BEFORE INSERT ON area_codes_markets
FOR EACH ROW
BEGIN
DECLARE tmp_market_id INT UNSIGNED;
DECLARE tmp_dr_market_id INT UNSIGNED;

IF NEW.market_id is null THEN
SELECT id
INTO tmp_market_id
FROM markets
WHERE dr_market_id = NEW.dr_market_id
;

SET NEW.market_id = tmp_market_id;
END IF;
END;|

delimiter ;

The trigger gives no warnings.
However when I try to insert a row into area_codes_markets, I get a foreign key constraints error:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`area_codes_markets`, CONSTRAINT `area_codes_markets_ibfk_1` FOREIGN KEY (`market_id`) REFERENCES `markets` (`id`))

The table 'markets' is populated with the correct ids.

Does anyone have an idea what I'm doing wrong?

If not, is there a way to print out the values of tmp_market_id and NEW.market_id in the trigger that are echo-ed to the console?

View Replies !
Generating DAILY Min&amp;Max Over A Period Of Time, Based On A "DateTime" Field
how to print the minimum and maximum of a specific field, between two datetimes (both having the time 02:00:00) - so I did this:

WHERE ((tblvalues.dtLPDateTime)>="2006-01-01 02:00:00" And (tblvalues.dtLPDateTime)<"2006-01-03 02:00:00"))

Now I want to print those min and max values but for each day in this cycle, i mean, for this example, there would be two records like:
Day Min Max
2006-01-01 02:00:00 -> 2006-01-02 02:00:00 | 40 | 59
2006-01-02 02:00:00 -> 2006-01-03 02:00:00 | 49 | 68
where at this point i`m getting min=40 and max=68

View Replies !
Updating Rows In Table B Based On Related Field In Table A
Ver 4.1.8-standard for apple-darwin7.6.0 on powerpc (Official MySQL-standard binary)

I am trying to do some data migration based. I have several tables that contain our legacy pkey field and I want to update the tables with new ID's.
I need to do this several times and have tried it several ways to no avail.

Table A
---------
companyID int(10) pKey
legacyID int(10) old legacy pkey

Table B
---------
bAID int(10) pkey
companyID int(10)
legacyID int(10)

Table A has values for both companyID (unique key) and legacyID.
Table B has values for bAID (unique key) and legacyID but companyID is empty.

I need to update tableB.companyID with tableA.companyID based on tableb.cSerialID to tablea.cSerialID relationship.

I need a query that will update ALL rows.

View Replies !
Updating Table Based Upon Matching Field In Second Table
I have a database of books that was originally created as a flat file.
Each record has a number of fields, including the authors name. I'm
trying to convert the database to something a little more efficient.
I've created a new table (called Authors) of unique authors names and
assigned each one a unique ID. I've added a new field in the original
table (called Books) for the author's ID. Now, I need to update the
original table with the author ID from the Author's table.

Something like this:

UPDATE Books SET AuthorID = Authors.AuthorID WHERE AuthorName =
Authors.AuthorName

This obviously doesn't work. Any assistance on how to forumulate this
query (or, if I'm headed down the wrong path, the correct way to do this
operation) greatly appreciated.

View Replies !
Select Based On FK
I have two questions regarding the MySQL v4.1.16 scenario below:

1. What should the FK on update and on delete parameters be (i.e., default, cascade, restrict, no action, etc.)?

2. How can I insert the correct id’s as implied below?

I have tried just about everything (including “Insert …select”, “LAST_UPDATE_ID();”, etc.) and whenever I think I am starting to get close I either get more errors or ‘0 records added’ with no error message;

I would greatlyappreciate someone who could instruct me on how to accomplish this task.

View Replies !
Using A Web Based Database
My web site host allows me to create MySQL databases on its database server. I've created a database as a trial. Now I would want users of my website to supply data to the database and for me to be able to extract it for analysis.

View Replies !
Web-based Chat
I'm debating between 2 different table setups for a web-based chat system (gchat clone). The first is just one table labeled 'chat' which has the columns 'user_1' 'user_2' 'time' 'message'. The second would be dynamically creating/deleting tables with the user names as table names like 'user_1/user_2'. I don't know a whole lot about DB table organization but I was thinking the actual 'select' statement would be faster with seperate tables. Any ideas?

View Replies !
UPDATE Based On Value In Another Table
How do I update a table to remove orphaned references to a second table? I've deleted rows in the second table, which has a unique auto_increment key. The first table now has references to keys that no longer exist. I need to update the first table, setting the value to NULL where the referenced key no longer exists. Something like:

UPDATE table1 SET table2ID = NULL WHERE table1.table2ID NOT FOUND IN
table2.ID;

The NOT FOUND IN isn't SQL, of course, but I'm not sure what should go there.

View Replies !
Union Based Upon First Query
I have a query that I would like to use a union statement in to grab the number of replies to a specific thread. The initial topic thread is in a different table, which I am grabbing in the initial query... I would prefer to do this in the single query, however I supposed I could do a separate loops and grab the number of replies with a totally distinct query ....

View Replies !
Syntax Based On MS Access SQL
Our shop is using an old version of MySQL (3.23).In testing our database concept we put together a test database in Access and the sql statement in MS Access looks like

SELECT DISTINCT FROM table1.col1, table2,col1
FROM table1, table2
WHERE (((table1,col1) like "*" & table2!col2 & "*"));

this gives us output from both tables(tables1 and tables2) while looping over the values of table2.col2.How does MySQL do this type of function?

View Replies !
SELECT Based On 2 Tables
I'm writing some custom stuff to pull from a WordPress install I have one one of my servers.

For one function I want to SELECT all the rows from one table based on criteria from that table and another table (they are related by the row ID of the first table). Here is the SQL I have now....

sql Code:
Original
- sql Code

SELECT DISTINCT t2.* FROM wp_term_relationships AS t1, wp_posts AS t2 WHERE t1.term_taxonomy_id = '4' AND t2.post_status = 'publish' AND t2.post_type = 'post' ORDER BY t2.post_date DESC

SELECT DISTINCT t2.* FROM wp_term_relationships AS t1, wp_posts AS t2 WHERE t1.term_taxonomy_id = '4' AND t2.post_status = 'publish' AND t2.post_type = 'post' ORDER BY t2.post_date DESC

It seems to be returning too many results. It's just returning all the rows from wp_posts that match the post_type and post_status criteria and ignoring the term_taxonomy_id (from wp_term_relationships) requirement.

View Replies !
Items Based On The First Letter
we have products database with CD's, and would like to create an alphabetical list of artists, then display the CD's that the artist has underneath them.
The database has the products in them, with the artists name being called 'prod_artist_name'. the query i tried, though I knew it wouldn't work is:

SELECT *
FROM products
WHERE prod_artist_name LIKE '%n%'

Now, this displays all the artists with the letter 'n' in their name, obviously. just wondering if there was a way to display the artists with 'n' as the first letter of their name.

View Replies !
Rows Based On First Letter
I'm trying to figure out the fastest/best way to return rows based on the first letter of the title column in my table. For example, I want to get all the article titles that start with the letter "a".
Is there any difference between the two select statements? Any reason to use one over the other? Memory? Speed?

SELECT title FROM table WHERE LEFT(title, 1) ='a';
or
SELECT title FROM table WHERE title like 'a%';

View Replies !
Sql Vs Text-based Databases
currently my site is storing data in text files, using explode() and seems pretty fast to me. would mysql be faster? i have a second box where i could set it up.

View Replies !
Update One Col From Another Col Based On Primary Key
I have a table which stores referral URLs in column 'ref' and primary key of the table is 'clid' I have added another column which will store the name of the search engine referral by the name 'SearchEngine'. Now what I want to do is to avoid PHP processing and write a mysql query as follow,

Code:

UPDATE clicks
SET SearchEngine=(
SELECT (
CASE WHEN (LOCATE('.google.',ref)!=0) THEN 'Google'
WHEN (LOCATE('.yahoo.',ref)!=0) THEN 'Yahoo'
WHEN (LOCATE('.msn.',ref)!=0) THEN 'Microsoft'
WHEN (LOCATE('.microsoft.',ref)!=0) THEN 'Microsoft')
WHEN (LOCATE('.live.',ref)!=0) THEN 'Microsoft')
ELSE 'Others' END
),
@tmpo:=clid
FROM clicks WHERE ref!=''
)
WHERE (clid=@tmpo);

but it gives me following error,

Code:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') WHEN (LOCATE('.live.',ref)!=0) THEN 'Microsoft') ELSE 'Others' END),clid:=@tm' at line 1

Basically i want to parse referral url, decide the search engine name and then store its name in the new column based on primary key so that correct values are stored in correct record.

View Replies !
Date Based Calculations
I'm looking for a way to create a query that generates a record for every day of the last year and using that date information for each day generates a unique database query (sub query?)for each day of the year.
I could probably do this in php but I'd like to do it for performance reasons from mysql (or at least most of it).
Does any one know of any good online tutorial/s that may help me build this sort of project? Or have some basic scripts that may be a good starting point?

View Replies !
Update Based On Another Table
Is it possible to do an update in MYSQL based on another table? I have version 3.23 and when I try to run this statement:


UPDATE ApplicationTbl
INNER JOIN AcademicTbl
ON ApplicationTbl.CampusID = AcademicTbl.CampusID
AND ApplicationTbl.Application_Period = AcademicTbl.Application_Period
SET ApplicationTbl.App_Status = 'Qualified'
WHERE AcademicTbl.Sem_OnCampus >= '1'
AND AcademicTbl.GPA >= '2.4'
AND AcademicTbl.Judicial_Sanction IS NULL

It keeps saying its wrong. Even though I know its not

View Replies !
Update One Column Based On Another
I have two tables. One set up like this:

id item_id group_id userid outcome settled

The second is

userid yes no

I would like to look at the first table and find all rows that have a specific group_id, then update the userid yes/no based on the outcome on that row. Outcome Y then add 1 to the yes column of that userid, outcome N then add 1 to the no column of the userid. Is this possible in one SQL statement?

View Replies !
I Need To Be Able To Get A Result Based On 2 Different Queries
I have a query that dislpays a pick up route. It shows a list of clients that needs to be serviced on any given day. Than I have a different query that displays all the clients that have been serviced on that particular day.

Now I need to show the clients that did not get the service that day.

View Replies !
Sql Based Contact Form
how would I create a contact form that would store the results in a sql databse, be able to see the results in a text file, and also would have a link to delete that result from the database in the results text file?

View Replies !
Timestamp Based Queries
I would just like some links or advice to information on how to do a query based on a timestamp.

Ie, I would like to find all the records in a movie database where was made after the year 2002.

View Replies !
Increment Based On Another Column
I'm having a little trouble working out the best way of doing something.

I'm storing a key split across two fields, the first field is 3 letters, the second is three numbers:
CREATE TABLE table1 (
id_a CHAR(3) NOT NULL,
id_b SMALLINT(3) NOT NULL,
...
);
What I'd like to do is have it so that when a new row is entered 'id_b' is calculated as MAX(id_b) + 1 WHERE id_a = new_id_a.

Is it safe to do this as some sort of nested query or is there a better way?

View Replies !
User Based PHP W/MySql
If I were to take a few different (gpl released) php programs that use MySql databases for the user data, could I integrate all the users into one database?
For instance, a user signs up in one of my forums, and their info is stored in a database. Then if they go to my auction script using the same database, they don't have to sign up again.

My guess is that yes it would work, but I'd have to go through each php file and edit where it called for the table data in each database to point to the same places.

View Replies !
Web Based MySQL Editor
I am looking for a Web Based MySQL Editor to manage, database, users, etc and if you can, tell me why you like it, good points, bad points, etc. I use PHPMyAdmin right now, so I am looking for something possibly better.

View Replies !
Retreaving Data Based
I have tables called room_status and room_info

room_status= room_id : date : status

room_info= room_id : type : rate

What I want to do is only make an entry in room_status when
a room is booked, as it is obviously available otherwise(duh) but
I don't know how to format a SELECT statement to bring back
rooms available on a specific date by only returning results from
the room_information table which do not have an entry in the room_status
table for a specific date, which is the case if I don't formally record that
a room is available.

View Replies !
Selecting Another Column Based On Max()
I've got a funky query I'm trying to set up. I've got this poll answers database, and each row has a qid that matches to a question. So I can group answers by the question they correspond to. Now I'm trying to select the total votes and the answer with the most votes for each question. The total votes part is working fine, but I'm having trouble with the winning answer part.

I've got a MAX(votes) that works well, and finds the answer with the most votes for every question, and returns its votes. What I want to do is select the `answer` column (the one that houses the actual text answer) of the answer with the greatest votes (the winner). Code:

View Replies !
SQL Selection Based On Date
I'm using this function / string to pull data based on yesterday:

$tomorrow = date('Y-m-d',strtotime('tomorrow'));

How can I pull data similarily based on "last month"?


View Replies !
Deleting Based On Subquery
i need to DELETE the results of this query :

SELECT bizName, COUNT( bizName ) AS name_count
FROM `datanewest` GROUP BY bizName
HAVING name_count >1
I use this to remove double entries. But when i run something lie this

DELETE FROM `datanewest` WHERE bizName IN (SELECT bizName, COUNT( bizName ) AS name_count
FROM `datanewest` GROUP BY bizName
HAVING name_count >1)
i get this error :

#1241 - Operand should contain 1 column(s)

View Replies !
Sql Statement Based On The Result Of Another?
I would like to use the result of one sql statement in another condition...

$select="select descr from ne_cats where " select sub_cat_id from ne_cats_rel, ne_cats where ne_cats_rel.cat_id='$cat_id'" "; .....

View Replies !
Ordering Based On Occurence?
I have this part of my query
SELECT DISTINCT country
FROM traffic_outgoing

and I want to limit it to the top 10 countries that have the highest number of occurences. How would I do that?

View Replies !
Selecting From One Table Based On Another?
I have a table for products

and another table for the type of product it is like this:

I need this is be in a seperate table because one product can be several different types like ring,band,wedding,three-stone,etc.

but how can I then select a product based on criteria from the types table

say I wanted to select all products that are type = "Band" and type != "Fancy" ?

View Replies !
Disk Based Cluster
I want to know mysql support disk based cluster. Because i want to migrate on mysql cluster 5.0 and i have 30 GB database. If i mysql disk based cluster supports that much space than that would be great.

Another question is that MyISAM storage engine in mysql supports table partioning ?

View Replies !
Select Based On Rarity?
I have a table and one column is titled "rarity." Every once in a while, ONE random row from this table will need to be selected... I want to select the random row based on the rarity column. All of the rarities would equal 1. For example, a rarity of .38 would have .38 probability of being selected from the table.

View Replies !
Getting Counts Based On Non-specified Date Ranges
I have a table which has, among other fields, a date field. I want to get a count of records where certain criteria are met for, say, three days in a row. For example:

NumWidgetsDate
11/1/2000
101/2/2000
201/3/2000
101/4/2000
151/5/2000
51/6/2000

I would like to know how many times 3 consecutive days have at least 10 widgets. In this case the answer is 1 because from 1/1/2000 to 1/3/2000 one day did not have at least 10 widgets, from 1/2/2000 to 1/4/2000 each day had at least 10 widgets, from 1/3/2000 to 1/5/2000, though all three days have at least 10 widgets, 1/3/2000 was already counted before so it should not count again, and from 1/4/2000 to 1/6/2000 one day did not have a least 10 widgets. Since 1/3/2000 was not counted before it would
otherwise qualify in the next set.

View Replies !
Creating A Query Based On Dates
I am trying to write a query (in PHP) which selects from a database all of the items which are in the future. My query is as follows

SELECT * FROM news WHERE ((news.date)>$today ORDER BY date

where news is my database, news.date is the the field which holds the date for the item and $today will be replaced my current date. At the moment it seems to display all values, which suggest its not functioning properly.

View Replies !
Enforce A Certain Constraint Based On Several Records
I'm trying to create a table "Works_In" as follows:

CREATE TABLE Works (
EID INTEGER NOT NULL,
DID INTEGER NOT NULL,
PctTime INTEGER NOT NULL,
PRIMARY KEY (EID, DID, PctTime),
FOREIGN KEY (EID) REFERENCES Employee (ID),
FOREIGN KEY (DID) REFERENCES Department (DID) );

The PctTime field shows the percentage of time that a given employee works in a given department (one employee can work in several departments).

My question is: how can I enforce that the PctTime value <= 100 ??

For example if the employee "John" works in Department "1" 20% of the time, and in Department "2" 80% of the time...how can I make sure that the total percentage is equal to 100%...

View Replies !
SELECT Based On All Day Names And Their Hours
I have a table which has a DATETIME column which stores datatime for each record.

I wanted to calculate the total/average of the records for each day and then for each hour of that day ALL TIMES like not only the current week or current month or year but for all available records.

a sample output can be

Monday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

Tuesday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

...

Sunday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

I tried something like following

SELECT count(id) as cnt,HOUR(hitdate) as hr, hitdate FROM hits GROUP BY DAYOFWEEK(hitdate),HOUR(hitdate)

And I am getting the following results, (long result)

cnt hr hitdate
1274 0 2008-07-27 00:00:50
1235 1 2008-07-27 01:00:07
921 2 2008-07-27 02:02:13
830 3 2008-07-27 03:00:03
674 4 2008-07-27 04:02:49
617 5 2008-07-27 05:00:37
606 6 2008-07-27 06:01:41
545 7 2008-07-27 07:01:52
534 8 2008-07-27 08:05:58
630 9 2008-07-27 09:04:01
680 10 2008-07-27 10:04:41
688 11 2008-07-27 11:01:26
881 12 2008-07-27 12:00:22
745 13 2008-07-27 13:00:09....

View Replies !
Joining Tables Based On Condition
I want to have a field determine what table the field should be joint on. For example, I have a field that is one of eight different values (contacts, leads, accounts, ect...). I want to be able to join on the specific table specified by the field because this field determines what type the id field corresponds to.

View Replies !

Copyright 2005-08 www.BigResource.com, All rights reserved