Showing posts with label multiple. Show all posts
Showing posts with label multiple. Show all posts

Friday, March 30, 2012

query help

I have a table with multiple records for an identical person. It is a rolling history of the applications a user has submitted. How can I grab the most current application by the date most closest to todays date. Obviously one of my fields is an applied date.
I need help in creating a query.select * from table t where datefield = (select max(datefield) from table where userid = t.userid)

Nick

Monday, March 26, 2012

query group by

have a table with records ranging from 0 to 100. some are repeated multiple
times, such as:
0
0
1
1
1
1
2
2
trying to figure out how to get a result that list the numbers and how many
times they each occur. such as.
num times
0 2
1 4
2 2
Any help would be appreciated. thanks,.SELECT num, COUNT(*)
FROM table
GROUP BY num
ORDER BY num
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Chad" <Chad@.discussions.microsoft.com> wrote in message
news:04CD49DB-34C4-4248-A874-5AFE88F4994C@.microsoft.com...
> have a table with records ranging from 0 to 100. some are repeated
multiple
> times, such as:
> 0
> 0
> 1
> 1
> 1
> 1
> 2
> 2
> trying to figure out how to get a result that list the numbers and how
many
> times they each occur. such as.
> num times
> 0 2
> 1 4
> 2 2
> Any help would be appreciated. thanks,.|||I miswrote what I was looking for. Actually looking for the numbers of a
range. such as:
0 thru 9 22
10 thru 19 89
20 thru 29 34
or should this be done in a presentation layer.
thanks,
"Aaron [SQL Server MVP]" wrote:
> SELECT num, COUNT(*)
> FROM table
> GROUP BY num
> ORDER BY num
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>
>
> "Chad" <Chad@.discussions.microsoft.com> wrote in message
> news:04CD49DB-34C4-4248-A874-5AFE88F4994C@.microsoft.com...
> > have a table with records ranging from 0 to 100. some are repeated
> multiple
> > times, such as:
> > 0
> > 0
> > 1
> > 1
> > 1
> > 1
> > 2
> > 2
> > trying to figure out how to get a result that list the numbers and how
> many
> > times they each occur. such as.
> > num times
> > 0 2
> > 1 4
> > 2 2
> >
> > Any help would be appreciated. thanks,.
>
>|||If you have a finite set of numbers, you could write some really elaborate
CASE logic. But I think this kind of thing is better done at the
presentation layer.
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Chad" <Chad@.discussions.microsoft.com> wrote in message
news:A7B99A2F-BF8A-46D0-B85F-78215711294A@.microsoft.com...
> I miswrote what I was looking for. Actually looking for the numbers of a
> range. such as:
> 0 thru 9 22
> 10 thru 19 89
> 20 thru 29 34
> or should this be done in a presentation layer.|||That can easily be done by applying integer division. In the query
below, NumRange represents the lower bound of the range.
create table #t (num int,val int)
insert into #t values (0,1)
insert into #t values (1,1)
insert into #t values (9,2)
insert into #t values (10,3)
insert into #t values (15,8)
SELECT (num/10)*10 NumRange,SUM(val)
FROM #t
GROUP BY (num/10)*10
ORDER BY NumRange
drop table #t
Gert-Jan
Chad wrote:
> I miswrote what I was looking for. Actually looking for the numbers of a
> range. such as:
> 0 thru 9 22
> 10 thru 19 89
> 20 thru 29 34
> or should this be done in a presentation layer.
> thanks,
> "Aaron [SQL Server MVP]" wrote:
> > SELECT num, COUNT(*)
> > FROM table
> > GROUP BY num
> > ORDER BY num
> >
> > --
> > http://www.aspfaq.com/
> > (Reverse address to reply.)
> >
> >
> >
> >
> > "Chad" <Chad@.discussions.microsoft.com> wrote in message
> > news:04CD49DB-34C4-4248-A874-5AFE88F4994C@.microsoft.com...
> > > have a table with records ranging from 0 to 100. some are repeated
> > multiple
> > > times, such as:
> > > 0
> > > 0
> > > 1
> > > 1
> > > 1
> > > 1
> > > 2
> > > 2
> > > trying to figure out how to get a result that list the numbers and how
> > many
> > > times they each occur. such as.
> > > num times
> > > 0 2
> > > 1 4
> > > 2 2
> > >
> > > Any help would be appreciated. thanks,.
> >
> >
> >

Friday, March 23, 2012

Query for multiple values

I was able to create a query that returns data based on a single order
number. Now I need to create a query that returns data based on
multiple order numbers. Obviously, when I run this query, it prompts me
for an order number. How do I change this so I can enter multiple order
numbers?
SELECT ORDNUMBE, CUSTNAME
FROM SOP10100
WHERE (ORDNUMBE = @.ordnumbe)
Thanks!http://www.sommarskog.se/arrays-in-sql.html
<2retread@.gmail.com> wrote in message
news:1126021459.621452.89010@.z14g2000cwz.googlegroups.com...
>I was able to create a query that returns data based on a single order
> number. Now I need to create a query that returns data based on
> multiple order numbers. Obviously, when I run this query, it prompts me
> for an order number. How do I change this so I can enter multiple order
> numbers?
> SELECT ORDNUMBE, CUSTNAME
> FROM SOP10100
> WHERE (ORDNUMBE = @.ordnumbe)
> Thanks!
>|||See if this helps:
Arrays and Lists in SQL Server
http://www.sommarskog.se/arrays-in-sql.html
AMB
"2retread@.gmail.com" wrote:

> I was able to create a query that returns data based on a single order
> number. Now I need to create a query that returns data based on
> multiple order numbers. Obviously, when I run this query, it prompts me
> for an order number. How do I change this so I can enter multiple order
> numbers?
> SELECT ORDNUMBE, CUSTNAME
> FROM SOP10100
> WHERE (ORDNUMBE = @.ordnumbe)
> Thanks!
>|||CREATE PROCEDURE Foobar ( <other parameters>, IN p1 INTEGER, IN p2
INTEGER, .. IN pN INTEGER) -- default missing values to NULLs
BEGIN
SELECT foo, bar, blah, yadda, ...
FROM Floob
WHERE my_col
IN (SELECT DISTINCT parm
FROM (VALUES (p1), (p2), .., (pN)) AS ParmList(parm)
WHERE parm IS NOT NULL
AND <other conditions> )
AND <more predicates>;
<more code>;
END;
In SQL Server, the VALUES() table constructor has to be faked with
(SELECT p1 UNION SELECT p2.. SELECT pn) AS Parmlist (p).|||On 6 Sep 2005 20:19:28 -0700, --CELKO-- wrote:

>CREATE PROCEDURE Foobar ( <other parameters>, IN p1 INTEGER, IN p2
>INTEGER, .. IN pN INTEGER) -- default missing values to NULLs
>BEGIN
>SELECT foo, bar, blah, yadda, ...
> FROM Floob
> WHERE my_col
> IN (SELECT DISTINCT parm
> FROM (VALUES (p1), (p2), .., (pN)) AS ParmList(parm)
> WHERE parm IS NOT NULL
> AND <other conditions> )
> AND <more predicates>;
><more code>;
>END;
>In SQL Server, the VALUES() table constructor has to be faked with
>(SELECT p1 UNION SELECT p2.. SELECT pn) AS Parmlist (p).
Hi Joe,
And how exactly is your query better than
SELECT foo, bar, blah, yadda, ...
FROM Floob
WHERE my_col
IN (p1, p2, .., pN)
AND <more predicates>;
?
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||I usually wind up adding some CAST(), UPPER() and other procedures to
the SELECTs or in theVALUES() list.|||On 7 Sep 2005 12:49:10 -0700, --CELKO-- wrote:

>I usually wind up adding some CAST(), UPPER() and other procedures to
>the SELECTs or in theVALUES() list.
Hi Joe,
Assuming that you meant "functions", not "procedures", there's still no
reason to make it so complicated:
WHERE my_col IN (UPPER(p1), CAST(p2 AS verchar(10), ..., LOWER(pN))
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||>> Assuming that you meant "functions", not "procedures", there's still no r
eason to make it so complicated: <<
Opps! I grant that you can do a lot of edit work with CASE epxrssions,
too:
CASE WHEN @.p1 NOT BETWEEN 1 AND 10 THEN NULL ELSE @.p1 END
But it is hard to do things that involve another table, such as
translating codes in the parameters to the target table format::
(SELECT shoesize_eur
FROM ShoeSizes.
WHERE UPPER (shoesize_usa) = @.p1)
or multiple-parameter look-ups:
(SELECT address_nbr
FROM StandardAddresseNumbers AS A
WHERE CAST (x_ord AS INTEGER) = @.p1
AND CAST (y_ord AS INTEGER) = @.p2)|||On 8 Sep 2005 07:57:01 -0700, --CELKO-- wrote:

>Opps! I grant that you can do a lot of edit work with CASE epxrssions,
>too:
>CASE WHEN @.p1 NOT BETWEEN 1 AND 10 THEN NULL ELSE @.p1 END
>But it is hard to do things that involve another table, such as
>translating codes in the parameters to the target table format::
>(SELECT shoesize_eur
> FROM ShoeSizes.
>WHERE UPPER (shoesize_usa) = @.p1)
>or multiple-parameter look-ups:
>(SELECT address_nbr
> FROM StandardAddresseNumbers AS A
> WHERE CAST (x_ord AS INTEGER) = @.p1
> AND CAST (y_ord AS INTEGER) = @.p2)
Hi Joe,
Assuming that we're still discussing what can and can't be placed in an
IN (expression, expression, ...) string, I still fail to see how CASE
expressions and subqueries like the examples you posted would introduce
the need to move from IN with a list of expressions to IN with a
subquery, like the one you posted at the start of this thread.
I don't have the full SQL-92 standard at my disposal, but Books Online
says this:
Syntax
test_expression [ NOT ] IN
(
subquery
| expression [ ,...n ]
)
Arguments
(snip)
expression [,...n]
Is a list of expressions to test for a match. All expressions must be of
the same type as test_expression.
There are no further requirements for the expressions in the list of
expressions. So you should bne able to just slam the subqueries in
there.
Of course, the end result would be quite complicated - but adding an
extra layer of complexity by using a subquery with SELECT .. FROM VALUES
(...) would make it even more complicated, not less so!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Query for multiple tables

Hi,

I have a query that returns values from three seperate data tables into a dataset:

SELECT [MediaFileData].[FileIdentifier], [AudioPCData].[RecorderID],
[AudioPCData].[Channel], [MediaFileData].[SubmittingUser], [MediaFileData].[DateTimeAsString],
[MetaData].[FieldText]

FROM [MediaFileData] INNER JOIN [AudioPCData] ON MediaFileData.FileIdentifier = AudioPCData.FileIdentifier
INNER JOIN [MetaData] ON MediaFileData.FileIdentifier = MetaData.FileIdentifier
INNER JOIN [SSRData] ON MediaFileData.FileIdentifier = SSRData.FileIdentifier

WHERE ([MediaFileData].[SubmittingUser] = '{0}') AND ([AudioPCData].[RecorderID] = '{0}')
AND ([MediaFileData].[MediaDescription] = '{0}') AND ([SSRData].[ModelUsed] = '{0}')

Each table has only got one 'FileIdentifier' apart from MetaData. This table has three columns 'FileIdentifer', 'FiledName' and 'FieldText'. One file can have more than one field and therefore It will have the same 'FileIdentifier' e.g.

FileIdentifier FieldName FieldText

1 Field 1 Hello

1 Field 2 Goodbye

The first problem is I only want to display the first and second field 'FiledText' in my results grid but still load all the other fields into my dataset.

The second problem is that it creates a new row for every field, whereas I want the fields with the same 'FileIdentifier' to be in the same row!

At the moment mt results gridlooks like this:

FileIdentifier RecorderID Channel SubmittingUser DateTimeAsString Field 1 Field 2

1 MyPC 1 Me 03/05/07 14:24 Hello Hello

1 MyPC 1 Me 03/05/07 14:24 GoodBye Goodbye

I need it to look like this:

FileIdentifier RecorderID Channel SubmittingUser DateTimeAsString Field 1 Field 2

1 MyPC 1 Me 03/05/07 14:24 Hello GoodBye

Thanks,

Guy

Depends on which version of SQL Server you are using. Using SQL 2k5 you should take a look on Cross apply.

Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||

Hi Guy,

Could you be more clear as to what your goal is, and what the purpose of these fields might be, their scope, the number of overlapping entries, and generally how you view this thing to be structured? On first blush, this seems like a situation where a relational database setup could save you some storage and access time in the long run if you can identify the shared fields and refactor your tables. The problem with setting Field1 and Field2 appropriately is also interesting in that you want Field1 to have "hello" in it and field2 to have "goodbye" in it whereas other than that string nothing differs between the records. This behaviour seems highly specific to your problem, and so knowing more about what your goals are for this database might help us to identify how best to solve your immediate problems in such a manner as to have long-term benefits.

Some natural things to weigh might be:

How do these components logically relate, and what are valid values for things in the database? (e.g. identical entries with field1 and field2 values, should this happen?, should field1 and field2 be mirrored?, etc.).

Does this solution need to last, or is it a one-time only operation?

How important is it to retain the database structure?

Is there a rule to how you want this join to work in the long run that requires domain specific knowledge?

How important is the performance of your database in the long run?

How often do you intend to perform this operation, and how much development work is "worth it"?

I think that as we understand the constraints of your task and what you intend to accomplish, we can find a solution that best fits your needs.

Thanks,

John (MSFT)

Friday, March 9, 2012

Query Data using multiple select statement

Hello everyone!

Is this statement is possible? here is the code:

select sum(nPassengers) Planned, Actual, (sum(Planned) - Actual) Variance
from (
select iDeptCode, sum(nPassengers) Planned from tbl_BusRequest
where iReqTime = '1' and iDeptCode = '1' and cReqType = 'I'
group by iDeptCode
and
(Actual = (Select nPassengers from tbl_Riders_NonRiders where dtDate = '11/05/06'
AND cReqType = 'i' and iTimeCode = '1' and iDeptCode = '1' )

and im getting this error:

Server: Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'and'.

Thankssee your previous post for the possible solution|||

Quote:

Originally Posted by intscript

Hello everyone!

Is this statement is possible? here is the code:

select sum(nPassengers) Planned, Actual, (sum(Planned) - Actual) Variance
from (
select iDeptCode, sum(nPassengers) Planned from tbl_BusRequest
where iReqTime = '1' and iDeptCode = '1' and cReqType = 'I'
group by iDeptCode
and
(Actual = (Select nPassengers from tbl_Riders_NonRiders where dtDate = '11/05/06'
AND cReqType = 'i' and iTimeCode = '1' and iDeptCode = '1' )

and im getting this error:

Server: Msg 156, Level 15, State 1, Line 6
Incorrect syntax near the keyword 'and'.

Thanks


You may want to put the results of the second 1/2 of your query in a temp table, then select from there.

A bit easier to read, if nothing else

Wednesday, March 7, 2012

Query Confusion -- Please help

I have three categories (cat1, cat2, cat3) that are updated each month at different times.
Cat1 may have multiple entries for the month.
I need monthly totals for each category and a monthly grand total for all categories.
Here is my problem. We have to start with a certain balance and continue from there. The balance for the end of January is the beginning value for February.
SELECT Sum(Transactions.cat1) AS SumOfcat1, Sum(Transactions.cat3) AS SumOfcat3, Sum(Transactions.cat2) AS SumOfcat2, Transactions.monthID, (sumofcat1+sumofcat2+sumofcat3) AS MonthlyTotal
FROM Transactions
GROUP BY Transactions.monthID
ORDER BY Transactions.monthID;
The above query returns the following
SumofCat1 SumofCat2 SumofCat3 MonthID MonthlyTotal
-- -- -- -- --
90 0 50 1 140
58 9 108 2 175
50 100 100 3 250
I need another field called GrandTotal that shows as follows
GrandTotal
140
315
575
Please help. I looked at the http://www.databasejournal.com/featu...le.php/3112381 site with the grand total tutorial, but can't get it to work in access.
hi jason,
Try following query:
select
SumOfcat1, SumOfcat3, SumOfcat2, monthID , (sumofcat1+sumofcat2+sumofcat3)
AS MonthlyTotal ,
(select sum(cat1)+sum(cat2)+sum(cat3)
from transactions a
where a.monthid <= x.monthid ) 'grandtotal'
from
(SELECT Sum(Transactions.cat1) AS SumOfcat1, Sum(Transactions.cat3) AS
SumOfcat3,
Sum(Transactions.cat2) AS SumOfcat2, monthID
FROM Transactions
GROUP BY monthID)X
ORDER BY monthID;
Vishal Parkar
vgparkar@.yahoo.co.in

Saturday, February 25, 2012

QUERY BY USER

I have a datagrid with rows that pertain to multiple users. I want to
write a query statement so that whomever the CURRENT logged-in
user is, he can go to the datagrid page and it will show ONLY rows
that pertain to him (programmatic security). To accomplish this,
I have a column in the datatable that references each user's
username. So I need a query statement that will compare the table's
'username' column to the current logged-in user. Something like...

SELECT... FROM [VendorEquipment]
WHERE [UserName] = Context.Current.User.Name

...or something like this. Question is, can someone help on how to
syntax this. Also, do I need anything special in the login form or in
web.config to 'pave the way' for this query to work.

Thx much.
Reid C.after a successfull login,you can store the username in sessions...|||Thanks for the reply...but I am a novice and will probably need more to clear up
the picture...can you suggest how I can syntax my SELECT command to accomplish
the above-stated objective and is there something I need to do via sessions to
enable this--and where would I do that?

Thx much.
Reid C.|||i believe you are checking for user authorization when the user logs in right ?

just put the username into session after the validation is successfull


session("username")=username

and frm any page
you can get it back as

dim uname as string
uname=session("username")

so when you query the db for the records you can do something like

strsql=select * From table where username='" & uname & "'"

and bind the datagrid.

HTH|||Thanks again...this sounds like what I'm looking for...just two
more questions due to my relative inexperience:

1) the statement: session("username")=username
you suggested...does that need to be in the login form
like in the "sub loginBtn_click" subroutine? and if so where in
the subroutine does it need to go...is the placement of the
statement critical?

2) is "username" interchangeable in this operation with "userid" ?
because I have written my registration form and login with a
"userid" instead of a "username"...but I will change this if it is
important to have "username" for forms authentication.

Thx.
Reid C.|||yep you can have any variable in session you want..username,userid...doesnt matter.
right after you check the userid with the password and if the query returns as a valid user, store the userid in sessions...and you should be able to access it frm any page...

HTH|||Thank you ...do I place the session stmt in global.asax?

like this, for instance:

Sub Session_OnStart()
Session("userId")=userId
End Sub


?

Thx.
Reid C.|||no...you put it in ur login.aspx where ever you validate the authenticity of the user...|||o.k., thanks again, ...but I am a complete novice and have been building pages
using WebMatrix, so sorry to be dense...but do I place the "session..." statement
in the "Function GetUser..." or in my "Sub LoginBtn_click..." subroutine, or after
that and right before the </script> tag ? I know placement of this statement is
important, I just don't know where?

Thx again.
Reid C.|||if you post your code for the login page..i can tell you where to place it...|||Thanks again for all your help...here is the code for the login (minus the html) and
I've got the statement placed right before the end </script> tag...tell me if you see
a glaring case of needing to move it to a more appropriate space.


<script runat="server">
Function GetUser(ByVal userId As String, ByVal userPassword As String) As System.Data.DataSet
Dim connectionString As String = "server='(local)'; trusted_connection=true; database='VSdatastore'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT [Users].* FROM [Users] WHERE (([Users].[UserId] = @.UserId) AND ([Users].[U"& _
"serPassword] = @.UserPassword))"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_userId As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userId.ParameterName = "@.UserId"
dbParam_userId.Value = userId
dbParam_userId.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userId)
Dim dbParam_userPassword As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userPassword.ParameterName = "@.UserPassword"
dbParam_userPassword.Value = userPassword
dbParam_userPassword.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userPassword)

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End Function
Sub LoginBtn_Click(Sender As Object, E As EventArgs)

If Page.IsValid Then
Dim userDS As New System.Data.DataSet
userDS = GetUser(UserId.Text, UserPassword.Text)
If userDS.Tables(0).Rows.Count = 1 Then
FormsAuthentication.RedirectFromLoginPage(UserId.Text, false)
Else
Msg.Text = "Invalid UserId or Password: Please try again"
End If
End If

End Sub
session("UserId")=UserId
</script


Thx again.
Reid C.|||i think this should work...

If Page.IsValid Then

Dim userDS As New System.Data.DataSet

userDS = GetUser(UserId.Text, UserPassword.Text)

If userDS.Tables(0).Rows.Count = 1 Then
'valid user...
session("UserId")=UserId

FormsAuthentication.RedirectFromLoginPage(UserId.Text, false)

Else

Msg.Text = "Invalid UserId or Password: Please try again"

End If

End If

End Sub

session("UserId")=UserId

|||In your revision you have the "session..." statement right after
the "If userDS.Tables(0).Rows.Count = 1 Then" statement which
made sense as soon as I saw it. But you also have the same
"session..." statement again after the "End Sub" statement. Is
this just a typo on your part from copying and pasting what I
sent you, or does it need to be there?

I am assuming it is a copy&paste oversight...unless you answer
back that it needs to be repeated...

Thx much again for your help.
Reid C.|||See if you can review the code for my datagrid page and see where I'm going wrong.
One thing, the "UserId" I need to compare is in the datatable as "PropUserId" because
I also have a column in the table "VendorUserId" and need to reference both. So I
need to compare the session "UserId" with the table's "PropUserId" column and I've
added a statement in the "Function GetVendorEquipment..." that says the "PropUserId"
column is equivalent to "UserId"...but I am getting a blank table on the page when I
run it.


<script runat="server"
Function GetVendorEquipment() As System.Data.DataSet
Dim connectionString As String = "server='(local)'; trusted_connection=true; database='VSdatastore'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)
dim UserId as String
dim PropUserId as String
PropUserId=session("UserId")
Dim queryString As String = "SELECT [VendorEquipment].* FROM [VendorEquipment] WHERE [PropUserId]='" & UserId & "'"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End Function

Sub Page_Load(sender As Object, e As EventArgs)
DataGrid1.DataBind()
End Sub

</script>

Thx again for your help.
Reid C.|||ur userid seems to be a number...
so you have to use


Dim queryString As String = "SELECT [VendorEquipment].* FROM [VendorEquipment] WHERE [PropUserId]=" & PropUserId

also one other suggestion...bind your datagrid within if not ispostback...loop


Sub Page_Load(sender As Object, e As EventArgs)
if not ispostback then
DataGrid1.DataBind()
end if
End Sub

HTH