SQL queries for finding values in 4 different tables
I need to have certain queries to find specific data in this table, this is just an example table, but I will use the same ideas for my actual website and database.
customers (customerID: integer, fName: string, lName: string)
items (itemID: integer, description: string, price: float)
orders (orderID: integer, itemID: integer, aID: integer, customerID: integer, date: date)
addresses (aID: integer, housenum: integer, streetName: string, town:string, state: string, zip:integer)
Values I need to find are
List the town, first name, and last name of any customer who has shipped an item to the same town as another customer.
Return the average amount of money each customer spent in March of 2013. (Note that the answer will be a single number
List the first and last names of all customers who have had the same item shipped to at least two different addresses.
List the top two states that have generated the most total revenue and the revenue they generated
I did try a few different queries, for #3 I tried
SELECT customers.fName,
customers.lName,
COUNT(orders.itemID) AS `total items with diff address >= 2`
FROM customers
JOIN (SELECT customerID,itemID,
COUNT(DISTINCT aID) AS diff_address
FROM orders
GROUP BY orders.itemID
HAVING diff_address >= 2
) AS orders
ON orders.customerID = customers.customerID
but I only got 1 result, and I do not think thats correct.
Thanks for the help and I appreciate you taking the time to help me
Why not post the sample data + desired result? Always state what version you are using.
SELECT lname,A.aID,COUNT(*) cnt FROM customers C JOIN orders O ON c.Customerid=O.Customerid
JOIN address A ON A.aID=O.aID
GROUP BY lname,aID
Sorry cannot test it right now...
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence
Similar Messages
-
Hi, Can I use Microsoft SQL Server Management Studio version 11.0 to write SQL queries for "SQL Server Compact 4.0 Local Database" ?
When I use Connect Object Explorer, the "Connect to Server" dialog box which pops up has only 4 selections in the Server Type Drop Down List. They are Database Engine, Analysis Services, Reporting Services & Integration Services. I have read
somewhere that there should be a compact database option. but I do not see it.
What I would like to do is use free form SQL Queries against the tables in "SQL Server Compact 4.0 Local Database" .
Once I have validated these queries, then I will use them in my Visual Studio 2012 C#, ASP.NET application. I created the Local Database using Visual Studio 2012 for use by my application.
Thank you for your help..
diana4Hello,
With SSMS 2005 we have had the Option to work with SQL CE database files, but not with higher Version of SSMS.
You can use the free SQL CE Toolbax instead; see
http://sqlcetoolbox.codeplex.com/
Olaf Helper
[ Blog] [ Xing] [ MVP] -
Sql queries for retrieving setups data for functional modules
Hi,
Can anyone give me the sql queries for retrieving setups data for functional modules (GL, AP, AR, FA, and CM) from Database.Hi,
Can anyone give me the sql queries for retrieving setups data for functional modules (GL, AP, AR, FA, and CM) from Database. -
Comparing row values in two different tables
Hello,
Does anyone know if it is possible to compare (and possibly highlight - which I know can be done) row values in two different tables?
I have a ZIP Code column in table A that I want to compare to a ZIP Code column in table B and highlight those ZIP Codes that are present in table B but not in table A etc. Is this possible?
Thanks,
KennethTo be able to apply conditional formatting, I must edit the formulas this way.
=IF(ISBLANK(B)," ",IF(ISERROR(VLOOKUP(B,Tableau 2 :: B,1,0))," ",VLOOKUP(B,Tableau 2 :: B,1,0)))
=IF(ISBLANK(B)," ",IF(ISERROR(VLOOKUP(B,Tableau 1 :: B,1,0))," ",VLOOKUP(B,Tableau 1 :: B,1,0)))
I replaces the four empty strings by strings containing one space character.
In the field supposed to contain the text which is not contained I just entered a single space character.
Yvan KOENIG (from FRANCE vendredi 12 septembre 2008 20:52:11) -
Hi Friends,
I Have a view named - item_sales with 4 column
Item code
Item name
Transaction_YYYYMM (Date stored in YYYYMM format )
QTY_RECEIVED
QTY_SOLD
Sample data is
ITEM_CODE ITEM NAME TRANSACTION_YYYMM QTY_RECD QTY_SOLD
AX TSHIRT 201307 3000 2000
AX TSHIRT 201308 2000 500
AX TSHIRT 201309 1000 3000
CX XLSHIRT 201307 3000 2000
CX XLSHIRT 201308 3000 2500
CX XLSHIRT 201309 3000 2500
EVERY MONTH END I WILL RUN THIS QUERY TO FIND OUT THE BELOW DETAILS
1. TO FIND ITEM_NAME WISE - QTY_RECEIVED AND QTY_SOLD ( FOR CURRENT MONTH - EXAMPLE SEP )
2. TO FIND ITEM_NAME WISE - QTY_RECEIVED AND QTY_SOLD (FOR CURRENT YEAR EXAMPLE FROM JAN TO SEP )
OUTPUT FOR SEPTEMBER MONTH LOOK LIKE THIS
SEP-MONTH JAN TO SEP
ITEM_CODE ITEM_NAME QTY_RECEIVED QTY_SOLD QTY_RECEIVED QTY_SOLD
AX TSHIRT 1000 3000 6000 5500
CX XLSHIRT 3000 2000 9000 7000
Pls advise me how to write queries for this
RdkJust FYI, you *can* edit your own posts, you know
Rdk wrote:
Transaction_YYYYMM (Date stored in YYYYMM format )
First "problem". Don't store dates as string. Store them as dates. It will save you so much headache don't the road you won't believe it.
True, this is a view, so maybe not as critical - assuming the underlying *DATA* is actually a date.
1. TO FIND ITEM_NAME WISE - QTY_RECEIVED AND QTY_SOLD ( FOR CURRENT MONTH - EXAMPLE SEP )
2. TO FIND ITEM_NAME WISE - QTY_RECEIVED AND QTY_SOLD (FOR CURRENT YEAR EXAMPLE FROM JAN TO SEP )
So yeah, based on these requirements, I'd recommend you make that column a DATE, not a string. Dates are easier to parse for date-related logic - such as month by month as you need here.
Using that, here's one way to do it:
with w_data as (
select 'AX' item_code, 'TSHIRT ' item_name, to_date('20130701','yyyymmdd') trans_dt, 3000 qty_recd, 2000 qty_sold from dual union all
select 'AX' , 'TSHIRT ' , to_date('20130801','yyyymmdd') , 2000 , 500 from dual union all
select 'AX' , 'TSHIRT ' , to_date('20130901','yyyymmdd') , 1000 , 3000 from dual union all
select 'CX' , 'XLSHIRT' , to_date('20130701','yyyymmdd') , 3000 , 2000 from dual union all
select 'CX' , 'XLSHIRT' , to_date('20130801','yyyymmdd') , 3000 , 2500 from dual union all
select 'CX' , 'XLSHIRT' , to_date('20130901','yyyymmdd') , 3000 , 2500 from dual
w_base as (
select item_code, item_name, trans_dt, qty_recd, qty_sold,
sum(qty_recd) over (partition by item_code, trunc(trans_dt, 'MM')) mm_recd,
sum(qty_sold) over (partition by item_code, trunc(trans_dt, 'MM')) mm_sold,
sum(qty_recd) over (partition by item_code, trunc(trans_dt, 'YY')) yy_recd,
sum(qty_sold) over (partition by item_code, trunc(trans_dt, 'YY')) yy_sold,
row_number() over (partition by item_code order by trans_dt desc) rnum
from w_data d
Select item_code, item_name, mm_recd, mm_sold, yy_recd, yy_sold
from w_base
where rnum = 1
IT ITEM_NA MM_RECD MM_SOLD YY_RECD YY_SOLD
AX TSHIRT 1000 3000 6000 5500
CX XLSHIRT 3000 2500 9000 7000 -
Hello All,
Can any body give me the total SQL queries which will be used in SAP.
Thanks&Regards,
Praveen KondabalaHi,
If you do need that kind of information, then it is easier that you do not use any.
> Like Oracle DBA
you only need to read the documentation about
1) brtools
2) dbacockpit (I assume you have a fairly recent SAP version)
you can find the information about this two "things" in
SAP on Oracle -
Tricky sql queries for interview preparation
Hi,
I need tricky sql queries as preparation for interview.
pls let me know if anybody has the such queries website address.
or
if you have materials pls mail me on
[email protected]
thnxNKU wrote:
Great Work Kamran....:-)
Regards,
Navneet;)
Kamran Agayev A. (10g OCP)
http://kamranagayev.wordpress.com
[Step by Step install Oracle on Linux and Automate the installation using Shell Script |http://kamranagayev.wordpress.com/2009/05/01/step-by-step-installing-oracle-database-10g-release-2-on-linux-centos-and-automate-the-installation-using-linux-shell-script/] -
Sql queries for this database schema
1) Patient—PatientID, Name, DOB
2) Doctor—DoctorID, Name, MedLicenseNumber, Phone
3) Medication—MedicationID, BrandName, GenericName
4) Prescription—PrescriptionID, Date, PatientID, PrescriberID, MedicationID
Specify the SQL queries to retrieve:
a) The prescription information along with patient name, DOB, medication brand name, and prescribing doctor name sorted by most recent date.
b) The most prescribed generic medication nameLooks like assignment question to me
a, seems to be a case of straight forward join among all the involved tables on common fields. Suggest you learn about joins and try it out yourself.
see below link
http://www.w3schools.com/sql/sql_join.asp
b, Have a look at GROUP BY. you need to apply group by and take medicine name which repeats maximum (ie largest count value)
see
http://www.w3schools.com/sql/sql_groupby.asp
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
A strange problem for Find Value Function
Hi, Dear
I have a strange problem for search Function, my SRM_SERVER is 550 and Package is SAPKIBKT11.
SRM_PLUS is SAPKIBK011.
When I use Find Value Function to find Cost Ctr, Such as:
Account object values = * (it is possible), Search Result: 300 Entries. I have no find my foucs data(12000)
But
Account object values = 12000, Search Result: 1 Entries,(Maximum No. of Hits is 500) I can find it. It is very jocularity.....Faint.
Please help me.
Thanks a lot.This is due to security permissions.
You can do one thing, edit C:\Jdk1.3(your java home)\jre\lib\security\java.policy and add the following line,
permission java.net.SocketPermission "*.*.*.109:1521-" "connect,resolve"; or
permission java.net.SocketPermission "shenpeng:1521-" "connect,resolve";
Save the file and run the applet from the command prompt. If this is not working, copy the java.policy file to C:\jdk1.3 (your java home) and execute the applet.
Hope this helps.
PS:- It is not recommended to access the database from applets. -
List rows with a certain value from a different table?
Hi,
I'm trying to list certain rows from a different table. Similar to the filter feature, kind of like a report.
To be specific, I have 12 tables (Jan-Dec) with many entries each (as rows). Each row has a date, text and further data. Now I want to create an additional table that lists rows from the other tables that have a certain date.
I would like to just enter that date in a header row cell so I can make a quick query. Using LOOKUP only shows the first row of that date. Is that even possible?Hi papalapapp,
If you don't mind using a script, you're using Numbers 3, and all of your monthly tables are on the same sheet, then you could do something like this:
Copy-paste script to Script Editor
Enter date you want to filter on in the designated filterCell (here A1 of the Extract table). Make sure it is formatted exactly like the dates in the monthly tables.
Clear any existing values from the Extract table, and make sure there are enough blank rows.
Click the run button in Script Editor.
SG
property targetTable : "Extract"
property filterCell : "A1"
tell application "Numbers"
tell document 1's active sheet
set dateFilter to table targetTable's cell filterCell's formatted value
--get all data in tables (excluding Extract table)
set vv to {}
repeat with t in tables
if t's name is not targetTable then
set vv to vv & t's rows's cells's formatted value
end if
end repeat
--filter data
set vvFilt to {}
repeat with i from 1 to vv's length
if vv's item i's item 1 is dateFilter then
set vvFilt to vvFilt & {vv's item i}
end if
end repeat
--write filtered data to table
tell table targetTable
repeat with r from 1 to (vvFilt's length)
repeat with c from 1 to vvFilt's item 1's length
set row (r + 1)'s cell c's value to vvFilt's item r's item c
end repeat
end repeat
end tell
end tell
end tell -
Sql query for finding a string in a column of a table
Hi All,
I have an issue, I have gotten a string ie '1D USD PRIME' and I have access to oracle's dictionary tables and views such as (all_source, all_tab_cols etc), my requirement is to find which table' column holds my above mentioned string, so I mean both the table name and the column name, it could be that this string might exist in more than 1 table so I want all the tables that holds it.
Regards
RahulHi All,
I think you misunderstood my question, so may be I didnt ask it properly, so here it is I am explaining in detail with an example.
Suppose I have 10 users with 10 different user name's in a database and I am the 11th user as DBA, every 10 of these users have created some tables lets say 20 tables each by every user making a count of the total tables as 200, now lets say 10 of 200 tables has a column ie fname with value as 'rahul', I want to search the string 'rahul' from all the 200 tables that which of the tables contains this string along with the column name.
I hope this time my question is clear, the point is I just know of a value and I dont know the table name and column name where it may actually residing, futher I want to search tables of other users as well.
Regards
Rahul -
SQL Queries for open sales orders with no invoice.
Hello all!
Is there a way to make a query to find out if there are any uninvoiced sales orders older than 5 days? I am having difficulty figuring out how the invoice is linked to the sales order.
I am more familiar with excel than SQL but I'm guessing it will be similar to the following:
SELECT * FROM ORDR WHERE today's date - posting date>5 AND (not sure what to check here for the invoice having been created)
**Note: my syntax is of course not exactly correct, this is just to give you an idea of what I'm looking for
Has anyone had to do this before or know how it would be done? It would be very useful for me.
Thanks!
MikeHi Mike
The document link is built on row level so the RDR1 should be used instead of ORDR to server your propose.
You could use this query to get all the lines do not link to a invoice.
*targettype 13 refers to target document invoice
select t0.docentry,t0.docdate,t0.linenum,t0.itemcode,t0.quantity,t0.price,t0.linetotal
from rdr1 t0 join ordr t1 on t0.docentry= t1.docentry
where t0.trgetentry is null and t0.DocDate < dateadd("d",-5, getdate()) and t1.docstatus = 'O'
or just use this query instead to find those lines do not link to any document
select t0.docentry,t0.docdate,t0.linenum,t0.itemcode,t0.quantity,t0.price,t0.linetotal
from rdr1 t0 join ordr t1 on t0.docentry= t1.docentry
where t0.targettype !='13' and t0.DocDate < dateadd("d",-5, getdate()) and t1.docstatus = 'O'
Please modify the code according to your needs.
Regards,
Syn Qin
SAP Business One Forums Team
Edited by: Syn Qin on Aug 11, 2008 5:20 AM -
Pl/sql expression for default value
I'm trying to run this simple script as a default value using pl/sql expression, but I keep getting this error. THe select statement itself works fine as a sql statement source value, but will not work as a pl/sql exression as a default value. This (:P33_SYSUSERID_CREATED_BY ) is the field name on the form. Any ideas?
begin
select a.id || ', ' || A.NAME_LAST into :P33_SYSUSERID_CREATED_BY from S_USERSV a where a.name_last = 'HAMMAKER';
end;
Error ERR-9132 Error in PLSQL expression for item default code, item=P33_SYSUSERID_CREATED_BY
OK
ORA-06550: line 1, column 27: PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following: ( - + case mod new not null avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date pipeSudha,
For a default value type of PL/SQL Expression, you could create a function that accepts an input and returns a value. If the function (not a procedure) is named GET_REFNO, you would call it using an expression in the default value field like:
get_refno(:P3_REFTYPE)
For a default value type of PL/SQL Function Body, you could call your existing procedure with a default value like:declare
l_value varchar2(32767);
begin
get_refno(:P3_REFTYPE, l_value);
return l_value;
end;Scott -
SQL query for updating values in same cell of a table
Hi All,
I'm stuck with a problem and it stands as follows:
Table name: Track
Part1 Part2 Part3
NULL NULL NULL
I've a table called Track, which has three columns named Part1, Part2 and Part3. I want all values of Part1 to be separated by a comma (,); it should not be overwritten, neither they should appear in separate row, in fact they should look like this:
Part1 Part2 Part3
1,2,3 5 SUBM1
The new values of Part1 should appear in next row only when value of Part3 changes, so if Part3 changes from SUBM1 to SUBM2, it should look like this:
Part1 Part2 Part3
1,2,3 5 SUBM1
1,2,3 5 SUBM2
Count of values in Part1 never exceeds the value of Part2, so if Part2 is 5, then Part1 will look like 1,2,3,4,5. So in other words loop will run only up to the value of Part2.
Please advise how this could be achieved?
Kind regards,
Aniruddha JagdaleI've a table called Track, which has three columns named Part1, Part2 and Part3. I want all values of Part1 to be separated by a comma (,);
No, don't go there.
This breaks a fundamental point for relational databases: no repeating groups. A cell should hold an atomic value. And this is not only a matter of purism. Relational databases are designed from this principle, and breaking this means that you will need
to write complex and higly inefficient code.
The values in Part1 should be in a separate table, with one value per row.
Erland Sommarskog, SQL Server MVP, [email protected] -
SQL Query for max values!!
Hi to all,
I have four tables
Tbl_one
Tbl_two
Tbl_three
Tbl_four
the relation between these tables is
Tbl_one.SEQ = Tbl_two.SEQ)
and tbl_two.case_SEQ = Tbl_four.SEQ
AND Tbl_two.ORDER_SEQ = tbl_three.SEQ))
I want a query like this
Select tbl_one.com_name, tbl_three.test_date,tbl_four.order_date
from Tbl_one,Tbl_two,Tbl_three,Tbl_four
where Tbl_one.SEQ = Tbl_two.SEQ)
and tbl_two.case_SEQ = Tbl_four.SEQ
AND Tbl_two.ORDER_SEQ = tbl_three.SEQ))
and tbl_three.test_date in (select max(test_date) from tbl_three)
and tbl_four.order_date in select(max(order_date from tbl_for)
and max(test_date)> Max(order_date)
any way it is possible?
the real problem is there are multiple test_dates and
multiple order_date for same seq in tbl_one.seq.
eg: -
name (indian) which has three or more test_date and each test_date have more than one order_date
indian (name) 01/01/2009(test_date) has ---- 01/10/2009, 01/20/2009 and 01/21/2009) order_dates
india(name) 02/02/2009 (test_date) has ----- 02/10/2009, 02/20/2009 and 02/30/2009 (order_dates)
india(name) 03/03/2009 test_date has ----- 03/10/2009, 03/20/2009 , 03/25/2009 (order_dates).
japan has the same situation and so on
what i wanted from the query is
max(test_date)= 03/03/2009 > max(order_date)=03/25/2009
ans: -
name
india(name) 03/03/2009 (test_date) 03/25/2009(order_date)
etc. etc . etc.
thanks!!
Edited by: pl/sql baby on Mar 24, 2009 10:45 AM
Edited by: pl/sql baby on Mar 24, 2009 10:47 AM
Edited by: pl/sql baby on Mar 24, 2009 10:51 AM
Edited by: pl/sql baby on Mar 24, 2009 10:57 AMPlease use tags either side of code / data (to preserve the formatting and spacing).
I don't understand your requirement... 03/03/2009 is not greater than 03/25/2009 ?
Could you please be clearer in your input/output samples and explain more about how to generate the output?
Maybe you are looking for
-
Mavericks upgrade from Mountain Lion deletes all user accounts
This is a lesson for upgrading too early (and too eagerly). Today I tried the Mavericks upgrade from Mountain Lion on my 2007 Macbook Pro, after going through all the pre-installation/pre-upgrade checklists. I don't think I have gone from a very high
-
Short dump error with InfoSource
Hi All, When i try to open Accounts Payable Infosource in BW production, It is returning with the short dump error ' Assertion was violated'. R_AWBOBJ ->. may I know what is this error. I created generic datasource in ECC DEV and replicated into BW D
-
Payment Proposal Error in Automatic Payment Program
While I am running the Automatic Payment Program Run after passing on the Parameters, I have created the Payment Proposal. When I am trying the edit the payment prosal to block payment of some of the invoice line items, system is throwling a red si
-
Failure: "might.cpp" line 815 on LabVIEW executable
Hi, I have a program written in LabVIEW 6.1 on a Windows XP platform. The program includes an ActiveX container that shows an Internet Explorer content window (just like the "Using the Microsoft Web Browser ActiveX Control" example found on http://si
-
Using Stored Procedures with TopLink / JPA : Success explanation
For those who have to use Stored Procedures in TopLink this is my success history : To call an Stored Procedure from the persistence, we have to use the direct JDBC connection because my TopLink version ( Essentials 10g ) ? to date ( 10g ) does not h