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 |
|
NewCents
Starting Member
19 Posts |
Posted - 2006-01-16 : 02:14:08
|
| Hmmm.can't figure this outI'd like to get a price total for all cases in the database where year=2005 and products_ID=33cases Table:cases_ID, year1, 20052, 20063, 2005casedetail Table:casedetail_ID, cases_ID, price, qty, product_code7, 1, 20, 2, 10118, 1, 30, 1, 10249, 2, 15, 5, 1000product_items Table:product_items_ID, cat_num, products_ID1, 1011, 332, 10122, 173, 3484, 224, 1024, 33The problem I'm having, the year is stored in the cases table. I'm using the query below to work off of. This query gets the total price of all casedetail entries which use that products_ID. It only works in one case. Select sum(qty*price) as price from (Select casedetail_ID, cases_ID, qty, price, (select top 1 products_id from product_items pi where pi.cat_num=cd.product_code) as products_id from casedetail cd) T where cases_ID=1 and products_ID in ('33') group by cases_IDSo with the dummy data above, this query would produce: $70.00I can't figure out how to join the cases table correctly, so I can add a where, like: 'where cases.year=2005'.Any help appreciated! |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2006-01-16 : 02:33:02
|
use INNER JOIN to join your tablesselect sum(d.price * d.qty) as total_pricefrom casedetail d inner join cases c on d.cases_ID = c.cases_ID inner join product_items p on d.product_code = p.cat_numwhere c.year = 2005and p.products_ID = 33 OR to group by Products_ID, Yearselect p.products_ID, c.year, sum(d.price * d.qty) as total_pricefrom casedetail d inner join cases c on d.cases_ID = c.cases_ID inner join product_items p on d.product_code = p.cat_numgroup by p.products_ID, c.year -----------------'KH' |
 |
|
|
NewCents
Starting Member
19 Posts |
Posted - 2006-01-16 : 12:08:12
|
| Hmm...I still need to incorporate this:select top 1 products_id from product_items pi where pi.cat_num=cd.product_codeSome how because there are multiple cat_num's that equal a specific products_ID. So I just need to get the first one. If I don't grab the first one than it will try and equate for every cat_num in the system. |
 |
|
|
NewCents
Starting Member
19 Posts |
Posted - 2006-01-16 : 17:22:11
|
| Okay, think I figured it out:Select sum(qty*price) as price from (Select casedetail_ID, cd.cases_ID, qty, price, c.DOSyear, (select top 1 products_id from product_items pi where pi.cat_num=cd.product_code) as products_id from casedetail cd inner join cases c on cd.cases_ID = c.cases_IDwhere DOSyear=2005) T where products_ID in ('33') This totals all cases in 2005 that had a casedetail with products_ID 33. |
 |
|
|
|
|
|
|
|