SQL Query Help - Using DropDownLists To Sort (multiple Variants)

Mar 15, 2007

Hi Everyone,
I am creating a portal and want the user to be able to select four variants from four separate drop down boxes... Such as chapter, story, etc... The user will then be able to click Find and shorten up the gridview list. The below query is what I am using for my current gridview (with custom paging). What I want to do is something like this:
 
Pass a variable such as @Story. If no Story is chosen, then the variable would be *. If a variable is chosen, the the @Story would the StoryID. However, I don't believe SQL recognizes the * in this case. I was thinking it should, but I don't believe it does. I was hoping it would just take it and I could write, SELECT * from Stories where StoryId=@Story, or something like that... and if * was @Story, then it would just select all... or if it was 1, then just stories with a StoryId of 1.
Am I totally off base here? Thanks!

 
CREATE PROCEDURE SortAllStories
@startRowIndex int,
@maximumRows int,
@totalRows int OUTPUT

AS

DECLARE @first_id int, @startRow int

SET @startRowIndex = (@startRowIndex - 1) * @maximumRows

IF @startRowIndex = 0
SET @startRowIndex = 1

SET ROWCOUNT @startRowIndex

SELECT @first_id = StoriesID FROM Storie ORDER BY StoriesId

PRINT @first_id

SET ROWCOUNT @maximumRows

SELECT Stories.StoryId, Chapters.ChapterName, Chapters.EnglishName, Translations.Translation,
Stories.Verse, Stories.Story
FROM Chapters, Stories, Translations
WHERE Chapters.ChapterId=Stories.ChapterId AND Translations.TranslationId = Stories.TranslationId  AND Stories.StoryId >= @first_id
ORDER BY Stories.StoryId


SET ROWCOUNT 0

SELECT @totalRows = COUNT(StoryId) FROM Stories

View 3 Replies


ADVERTISEMENT

Need Help Adding Multiple Values To Dropdownlists Datatextfield

Jan 15, 2004

I'm trying to put a range of dates into the datatextfield of my ddl. I'm using the query:

string strProps2 = "SELECT sc_id, cast(begin_date AS varchar) + ' - ' + cast(end_date AS varchar) AS XYZ From Archived_Property_Changes WHERE Property_number = " + qryPN + " ORDER BY end_date";

but it gives me an empty ddl. the datavaluefield shows the correct results, but it's not displaying the correct data from the datatextfield. I removed the casts from the SQL query and it returns:

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value

Below is my ddl code:

SqlCommand objCommandProps2 = new SqlCommand(strProps2, myConnection);
SqlDataReader objReaderProps2 = objCommandProps2.ExecuteReader();

ddlArchive.DataSource = objReaderProps2;
ddlArchive.DataValueField = "sc_id";
ddlArchive.DataTextField = "XYZ";
ddlArchive.DataBind();
ddlArchive.Items.Insert(0, "Select A Period");

Any thoughts are duely appreciated...

View 2 Replies View Related

SQL 2012 :: Parameterized Sort On Multiple Keys Possible?

Oct 13, 2014

I have sp that works with GUI and have an opton for sort field/ collation. But I noteiced that if I do level on very generic key like <Level> in my case it does the job, but output does'nt look right after that all names, account numbers are messed, so I'd like to add second sort column and looks like it can'be be done with my syntax, I tried to play adding second column and failed.

Select * from T1 order by Level, FirstName

Looks like it only can be done with Dynamic...

DECLARE @SortColmn VARCHAR(10) = 'Level'
SELECT *
FROM TABLE
CASE WHEN @SortColmn = 'FirstName' AND @SortDir = 0 THEN FirstName END DESC
,CASE WHEN @SortColmn = 'LastName' AND @SortDir = 0 THEN LastName END DESC
,CASE WHEN @SortColmn = 'Region ' AND @SortDir = 0 THEN Region END DESC
,CASE WHEN @SortColmn = 'Level' AND @SortDir = 0 THEN [Level] END desc --<@>>< THEN FIrstName asc ???

View 1 Replies View Related

2 DropdownLists 1 SQLDataSource

Jan 19, 2007

I have 2 dropdownlists that use different fields from 1 SQLDatasource. I want one of the dropdown's to be a main dropdown that users will see, the other will be invisible. When a user changes the main dropdown and it does a postback, I want the second to also go to the record that the main one is on.The reason being is that I have a lot of SQLDatasource's on one page, most of them take an ID parameter but some SQLDatasource's need a CODE parameter. I can't think of any other way to parse the code parameter. I want to use a control parameter for the SQLDatasource's to pass the CODE from the invisible dropdown but obviously I need it to go to that record when the main dropdown changes

View 2 Replies View Related

Sort Results By Rank Using FREETEXT On Multiple Columns

Apr 20, 2008

Hi,I am using MS SQL server 2005 and wondering how to sort my results by rank using FREETEXT on multiple columns.  Is there a way to do this? My two colums are:title and description
 
can anyone give any code snippets?

View 1 Replies View Related

SQL Server 2008 :: Multiple Languages In Same Column - How To Sort / Select

Jul 29, 2011

We have a database where the nvarchar columns currently holding English only data. It keeps the training information. Currently the default collation is Latin Case insensitive accent insensitive.

Now we are planning to allow multiple language support. When we go for it, we will upload the data from different languages. Based on user preferences, he/she should be able to query the data (One language at a time).

I am worried on how the existing queries will work if I load all language data in the same database.

For example, some characters in English are used in Norwegian too. But they have different sort order. ALso LIKE conditions too may fail.

So far I thought of few solutions: Add the Collation information along with select , order by clauses. It means we need to add more procedures (one set per collation) The other option is to create new database for each language. Each will have its own collation. The dowside is we need more databases which may lead to more servers and more maintenance work.

View 9 Replies View Related

Using One SqlDataSource For Many DropDownLists, But Ability To Set Parameters?

Jan 3, 2007

If I have a lot of dropdowns of similar type but only differ in one field, is there a way to set parameters so that the dropdownlist can specify what the parameter values are?
 For example dropdowns: expenseaccount, incomeaccount, assetaccount
SqlDataSource:
SelectCommand="select accountid,accountname from accounts, accounttypest where accounts.accounttypeid=acounttypes.accounttypeid and accounttypes.accounttypename=? order by accountname"
<SelectParameters>
<asp:Parameter Name="accountTypeName" Type="string" />
</SelectParameters>
 -------
I would like expenseaccount to be able to specify "EXPENSE", incomeaccount to specify "INCOME", etc...
 Or is sqldatasource reusage bad practice?
(damn vs2k5 colors)

View 7 Replies View Related

How To Bind Data Retrived From Sql Db To DropDownLists?

Jun 20, 2007

 Hello all,I just have problems to bind the data to dropdownlists, and my code is written as:  SqlConnection myConnection;            SqlCommand myCommand;            SqlDataReader myReader;            myConnection = new SqlConnection();            myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;            myCommand = new SqlCommand();            myCommand.CommandText = "select PostalCode from Customers order by PostalCode asc";            myCommand.CommandType = CommandType.Text;            myCommand.Connection = myConnection;            myCommand.Connection.Open();            myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);            DropDownList1.DataSource = myReader;            DropDownList1.DataBind();            myCommand.Dispose();            myConnection.Dispose();Any idea? Thanks 

View 3 Replies View Related

Can Save Labels To The DB But Not The Content Of DropDownLists !

Jul 28, 2007

hi there, i have a payment page which uses javascript to calculate payments and what remains etc. That all works fine, the problem i have is that when you are finished and you go to the next page it should save all of the records to the order table where the order_id = a querystring. Now i have tried using an insert method and an update method, not really sure whats the difference when putting data into an existing record. What happens though is that i can save the contents of labels etc but it wont save the content of dropdown lists (of which there are 2) i just cant work it out, i have posted my code below
 string strOrderID = Convert.ToString(Request.QueryString["OrderID"]);
string strDiscountPercent = Convert.ToString(5656);double dblDiscountMoney = Convert.ToDouble(txtDiscountMoney.Text);
string strPaymentMethod1 = ddlPaymentMethod1.SelectedValue;double dblPaymentAmount1 = Convert.ToDouble(txtPaymentAmount1.Text);
string strPaymentRecipt1 = txtPaymentRecipt1.Text;string strPaymentMethod2 = ddlPaymentMethod2.SelectedValue;
double dblPaymentAmount2 = Convert.ToDouble(txtPaymentAmount2.Text);string strPaymentRecipt2 = txtPaymentRecipt2.Text;
 string sConnectionStringCustInfo = "my connection string";
SqlConnection objConnOID = new SqlConnection(sConnectionStringCustInfo);
//This is the sql statement.using (objConnOID)
{
objConnOID.Open();
 string sqlUpDate = "UPDATE tbl_order SET discount_Percent = " + txtDiscountPercent.Text +
", discount_money = " + dblDiscountMoney + ", payment_method1 = " + strPaymentMethod1 +   =========== this is the problem line here!
", payment_amount1 = " + dblPaymentAmount1 + ", payment_ref1 = " + strPaymentRecipt1 +
", payment_amount2 = " + dblPaymentAmount2 +", payment_ref2 = " + strPaymentRecipt2 +
 
"WHERE order_ID = " + strOrderID;
 
 
 
SqlCommand objCmd1 = new SqlCommand(sqlUpDate, objConnOID);
 
try
{
 
objCmd1.ExecuteNonQuery();
}
 
and because it throws an error it wont update the database with any other record. does anyone have any ideas, i have spent hours last night trying to figure this one out and im sure its simple! but i need some help!
 
Cheers
Jez

View 5 Replies View Related

DropDownLists Edit In Grid View To Display Names But Have Value Of User_ID ... Possible?

Mar 16, 2008

Hello,I have inserted a drop down list in my Edit template of Grid view.  This DDL should control the User_ID who is responsible for the Computer being edited.  However I want it to display the User Names rather than the user IDs.  I have a COMPUTERS and a USERS table.  They are related by having User_ID in both.  Below is my grid view with the parts i feel relative highlighted in bold:<asp:GridView ID="GridView1" runat="server" AllowSorting="True"         AutoGenerateColumns="False" DataKeyNames="Computer_ID"         DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333"            GridLines="None">           <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />           <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />        <Columns>            <asp:CommandField ShowEditButton="True"/>            <asp:BoundField DataField="Computer_ID" HeaderText="Computer_ID"                 InsertVisible="False" SortExpression="Computer_ID" ReadOnly="true" />            <asp:BoundField DataField="Computer_Name" HeaderText="Computer Name"                 SortExpression="Computer_Name"/>            <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer"                 SortExpression="Manufacturer"/>            <asp:TemplateField HeaderText="User Name" SortExpression="Name">                <EditItemTemplate>                    <asp:DropDownList ID="DDL_Name" runat="server" DataSourceID="SQLDataSource2" DataValueField="User_ID" SelectedValue='<%# Bind("User_ID") %>'></asp:DropDownList>                </EditItemTemplate>                <ItemTemplate>                    <asp:Label ID="lblName1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>                </ItemTemplate>            </asp:TemplateField>        </Columns>              <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />           <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />           <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />           <EditRowStyle BackColor="#999999" />           <AlternatingRowStyle BackColor="White" ForeColor="#284775" />    </asp:GridView>    <asp:SqlDataSource ID="SqlDataSource2" runat="server"        ConnectionString="Data Source=.SQLEXPRESS;AttachDbFilename=C:AjaxControlToolkitWebSite1App_DataAssetDatabase.mdf;Integrated Security=True;User Instance=True"         ProviderName="<%$ ConnectionStrings:AssetDatabaseConnectionString.ProviderName%>"         SelectCommand="SELECT * FROM USERS" >    </asp:SqlDataSource>    <asp:SqlDataSource ID="SqlDataSource1" runat="server"        ConnectionString="Data Source=.SQLEXPRESS;AttachDbFilename=C:AjaxControlToolkitWebSite1App_DataAssetDatabase.mdf;Integrated Security=True;User Instance=True"         ProviderName="<%$ ConnectionStrings:AssetDatabaseConnectionString.ProviderName%>"         SelectCommand="SELECT COMPUTERS.Computer_ID, USERS.User_ID, COMPUTERS.Computer_Name, COMPUTERS.Manufacturer, USERS.Name FROM COMPUTERS INNER JOIN USERS ON COMPUTERS.User_ID = USERS.User_ID"         UpdateCommandType="StoredProcedure" UpdateCommand="StoredProcedure1"          >        <UpdateParameters>            <asp:Parameter Name="Computer_ID" Type="Int32" />             <asp:Parameter Name="User_ID" Type="Int32"/>             <asp:Parameter Name="Name" Type="String" />             <asp:Parameter Name="Computer_Name" Type="String" />            <asp:Parameter Name="Manufacturer" Type="String" />        </UpdateParameters>    </asp:SqlDataSource>    <br />    <br />    </form></body></html>  THANKS =] 

View 6 Replies View Related

Sort MDX Query

Feb 28, 2005

Trying to get data from result of MDX query in dec order:

iLoopFrom = cst.Axes(1).Positions.Count - 1
iLoopTo = 0
iLoopStep = -1

im using these lines to read the data from bottom to top but what exactly does Position.Count do? and is the -1 there because the result has headers??

Thanks

View 1 Replies View Related

SQL Server Query Sort

Jan 2, 2007

I'm trying to find a way to sort my query like the following:
 SELECT * FROM tbl_Post WHERE ID = 3 OR ID = 1 OR ID = 4 OR ID = 2 ORDER BY (3,1,4,2)
 Now if ID is my primary key, the sort by default would be 1, 2, 3, 4.
 I would like to specify order so that I could return the order as 3, 1, 4, 2 if I wanted to.
 Is there any way to do this?
Thanks,Russ

View 2 Replies View Related

How To Sort Data Using SQL Query

Dec 18, 2007

Dear All,

i need your help,

i had created a table student, studentid column with alpha numeric primary key with varchar datatype

now my problem: i want to sort the student id accroding to studentid like

STU1
STU2
STU3
STU4
STU5
.
.
.
STU9
STU10
STU11

but i’m getting the sorted result like this, how to overcome this problem,guide me PLEASE

STU1
STU10
STU11
STU12
.
.
.

STU100
.
.
.

STU1000
STU10000
STU2
STU20
STU200
STU2000
STU20000
STU20001


Thank's In Advances

View 9 Replies View Related

Sort Result According The Query

Feb 27, 2005

I have a query:
SELECT *
FROM Mobile_Subscriber
WHERE (sub_ID IN (17, 2, 19))

The result return:
sub_ID sub_name
2 John
17 Alice
19 Eddy

But what I want is:
sub_ID sub_name
17Alice
2John
19Eddy

Is it possible to return the result order by the query with: sub_ID IN (17,2,19)?

View 3 Replies View Related

SELECT, SORT, And SUM Query

Oct 14, 2005

Hello everyone,

I Have a table with columns:
- CustomerID
- DateTransactionCompleted
- AmountPaid

Illustration data as follow

GO
INSERT INTO Cus_Tab_Dev_2 VALUES(30,'12-12-2004','18000.00')
INSERT INTO Cus_Tab_Dev_2 VALUES(30,'12-15-2004','2000.00')
INSERT INTO CUS_Tab_Dev_2 VALUES(30,'1-16-2005','15000.00')
INSERT INTO CUS_TAB_DEV_2 VALUES(42,'2-2-2005','12000.00')
GO

What I want is a report that tells me the Total Sales per month Per Customer in the following manner:

Customer ID Month/Year Total Per Month
----------- ----------- ----------------
30 12-2004 20000.00
30 1-2005 15000.00
42 2-2005 12000.00

This is a homework, and I have been trying to get it to work since this morning. Any help is appreciated.

PS: If you do not feel you want/should help. Please don't call me names! I don't ask people to help me with my homework usually. But, I am running out of time on the assignment.

View 4 Replies View Related

Some Sort Of Cross Tab Query In Sql

Jul 23, 2005

I have three tables:tblBook has the fields bookID, bookRangeID, bookSubjectID, bookCodetblBookRange has the fields bookRangeID, bookRangeDescriptiontblBookSubject has the fields bookSubjectID, bookSubjectDescriptionso some typical data in tblBook might be:1, 1, 1, B1HBSCI2, 1, 2, B2HBFRE13, 1, 3, B3HBGER4, 2, 1, B4PBSCI5, 2, 2, B5PBFRE6, 2, 3, B6PBGER7, 3, 1, B7CDSCI8, 3, 2, B8CDFRE9, 3, 3, B9CDGER110, 3, 3, B10CDGER211, 1, 2, B11HBFRE2tblBookRange would be:1, HardBack2, PaperBack3, CD RomtblBookSubject would be:1, Science2, French3, GermanI'd like to create a query which will return me the subjects along thetop, the book range down the side, and the bookcodes in the cells, abit like this:BookRange , Science, French, GermanHardBack , B1HBSCI, B2HBFRE1 B11HBFRE2, B3HBGERPaperBack , B4PBSCI, B5PBFRE, B6PBGERCD Rom , B7CDSCI, B8CDFRE, B9CDGER1 B10CDGER2Does that make any sense? So basically I'd like to get some kind ofdynamic SQL working which will do this kind of thing. I don't want tohard code the subjects in or the book ranges. I get the feeling thatdynamic SQL is the way forward with this and possibly using a cursor ortwo too, but it got quite nasty and convoluted when I tried variousattempts to get it working. (one of the ways I tried included workingout each result in a dynamic script, but it ran out of characters asthere were too many "subjects".)If anyone has any nice but quite dynamic solutions, I'd be delighted tohear.(and I know some of you have already told me you don't like tablesbeginnig with tbl, but I'm not hear for a lecture on namingconventions, I'm hear to learn and share ideas :o) )

View 2 Replies View Related

Query Sort Question

Jul 20, 2005

I have a field called "type" in my "school" table that can have threepossibilities:ElementaryMiddleHighIn my result set, I always want Elementary to come first, Middle tocome second, and High to come third. An alpha sort gets me this:ElementaryHighMiddleSure, I could create a look-up that assigns an integer to the "type"field to get the right sort order (i.e. elementary = 0, middle = 1,high = 2) ... but is there a better way to do this with SQL syntax?Thanks,Ralph NobleJoin Bytes!

View 1 Replies View Related

Sort On Field Constructed In Query

Aug 3, 2007

I want to sort on a field that I construct during a query....how can I solve this?Basically what i am doing is selecting mediafiles with comments in descending order. (so mediafile with most comments on top)Here's my (not working) query, because it throws the error that the mediaComments column is unknown....SELECT *FROM(select ROW_NUMBER() OVER (ORDER BY mediaComments DESC) as RowNum,m.title,m.usercode,mediaComments=(select count(*) from MediaComments where mediaid=m.mediaid)FROM Media m WHERE m.usercode>0group by  m.title,m.usercode) as InfoWHERE RowNum between @startRowIndex AND (@startRowIndex + @maximumRows-1)

View 4 Replies View Related

Dynamic Sort Column And Sort Order Not Working

Aug 7, 2007

I am trying to set sorting up on a DataGrid in ASP.NET 2.0.  I have it working so that when you click on the column header, it sorts by that column, what I would like to do is set it up so that when you click the column header again it sorts on that field again, but in the opposite direction. I have it working using the following code in the stored procedure:   CASE WHEN @SortColumn = 'Field1' AND @SortOrder = 'DESC' THEN Convert(sql_variant, FileName) end DESC,
case when @SortColumn = 'Field1' AND @SortOrder = 'ASC' then Convert(sql_variant, FileName) end ASC,
case WHEN @SortColumn = 'Field2' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, Convert(varchar(8000), FileDesc)) end DESC,
case when @SortColumn = 'Field2' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), FileDesc)) end ASC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'DESC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end DESC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end ASC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, FileDataID) end DESC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'ASC' THEN CONVERT(sql_variant, FileDataID) end ASC  And I gotta tell you, that is ugly code, in my opinion.  What I am trying to do is something like this:  case when @SortColumn = 'Field1' then FileName end,
case when @SortColumn = 'FileDataID' then FileDataID end,
case when @SortColumn = 'Field2' then FileDesc
when @SortColumn = 'VersionNotes' then VersionNotes
end

case when @SortOrder = 'DESC' then DESC
when @SortOrder = 'ASC' then ASC
end  and it's not working at all, i get an error saying:  Incorrect syntax near the keyword 'case' when i put a comma after the end on line  5 i get: Incorrect syntax near the keyword 'DESC' What am I missing here? Thanks in advance for any help -Madrak 

View 1 Replies View Related

How To Write A SQL Query To Sort A Table With The Priority Column As Well?

Jan 16, 2005

Hi,

Anyone can help me for the Sql query?

I want to sort a table with a priority column, e.g. in the following...

Table A
======
value
======
9
3
1
7
4
======

After sorting:

Table A
========
no value
========
1 1
2 3
3 4
4 7
5 9
========


Anyone can help me?
Thanks.

Daniel.

View 1 Replies View Related

SQL 2012 :: How To Find Query Which Have Sort Warning Alert In Profiler

Jan 30, 2015

which have a lot of impact to database performace since it do not fit onto memory and spill over to disks.

The question is when i ran a profiler and tried to catch a sort warning i cannot find the query which cause the alert.

View 1 Replies View Related

Transact SQL :: Query To Return Greater Than Zero Values To Sort Up And Zeros Go Down

Sep 17, 2015

I am using a table to store different size numbers for example:

Look at the picture below:

But I want this type of output look at the picture below:

How to sort the query to return greater than zero values to sort up and zeros go down. 

I am using sql server 2008.

View 14 Replies View Related

Am Using Sql Server 2005, Column Data Type Is Varchar, How To Write A Query To Sort

Aug 2, 2006

this data. need help
Sort following numbers by asc and desc order

Before query sort
-1.1
-8.8
-15.5
0.0
+0.5
+0.2

Sort asc
+0.5
+0.2
0.0
-1.1
-8.8

Sort Desc
-8.8
-1.1
0.0
+0.2
+0.5












View 5 Replies View Related

Transact SQL :: Query To Convert Single Row Multiple Columns To Multiple Rows

Apr 21, 2015

I have a table with single row like below

 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Column0 | Column1 | Column2 | Column3 | Column4|
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Value0    | Value1    | Value2    | Value3    |  Value4  |

Am looking for a query to convert above table data to multiple rows having column name and its value in each row as shown below

_ _ _ _ _ _ _ _
Column0 | Value0
 _ _ _ _ _ _ _ _
Column1 | Value1
 _ _ _ _ _ _ _ _
Column2 | Value2
 _ _ _ _ _ _ _ _
Column3 | Value3
 _ _ _ _ _ _ _ _
Column4 | Value4
 _ _ _ _ _ _ _ _

View 6 Replies View Related

One Receipt Number, Query Multiple Tables Gives Multiple Data.

Sep 8, 2006

I have just taken over the job of sorting out a rather poorly designed database. It looks like it was 'upsized' from an access database to the SQL server. The SQL server is the 2000 version.

Now I am trying to generate a report of what the students in the database are owing by referencing the Receipt table and then all the available payment methods and allocations. I was wondering if there was anyway to work out data being displayed twice (Let me demonstrate)

Note1: All the tables are linked by a key of ReceiptNo. From what I can see there is a table for every payment type and allocation but no link between the two other then the receipt number.

Using the query:
SELECT T_Receipt.ReceiptNo, T_cheque.Amount AS Chq_Amount, T_credit.Amount AS Cre_Amount, StandingOrder.Amount AS Stn_Amount,
T_BankTransfer.amount AS Bnk_Amount, T_cash.TotalAmount AS Cas_Amount, T_RentPayment.AmountPayed AS Ren_Paid,
T_AdminPayment.AmountPaid AS Adm_Paid, T_InternetBilling.Total AS Int_Paid, T_Utilities.AmountPaid AS Util_Amount,
T_InvoicePayment.amountPaid AS Inv_Paid, T_OtherPayments.paymentAmount AS Oth_Paid, T_parkingBill.paymentAmount AS Prk_Paid,
T_TelephoneBills.TelephoneCredit AS Tel_Paid, T_DepositPayment.[Deposit payment] AS Dep_Amount, T_Receipt.cancelled AS Canceled,
T_Receipt.RemittanceReceiptNo AS Rec_Ref, T_Receipt.Student
FROM T_Receipt INNER JOIN
T_DepositPayment ON T_Receipt.ReceiptNo = T_DepositPayment.receiptNo LEFT OUTER JOIN
T_RentPayment ON T_Receipt.ReceiptNo = T_RentPayment.RentPaymentNo LEFT OUTER JOIN
StandingOrder ON T_Receipt.ReceiptNo = StandingOrder.ReceiptNo LEFT OUTER JOIN
T_TelephoneBills ON T_Receipt.ReceiptNo = T_TelephoneBills.ReceiptNo LEFT OUTER JOIN
T_parkingBill ON T_Receipt.ReceiptNo = T_parkingBill.ReceiptNo LEFT OUTER JOIN
T_OtherPayments ON T_Receipt.ReceiptNo = T_OtherPayments.ReceiptNo LEFT OUTER JOIN
T_InvoicePayment ON T_Receipt.ReceiptNo = T_InvoicePayment.receiptNo LEFT OUTER JOIN
T_cash ON T_Receipt.ReceiptNo = T_cash.ReceiptNo LEFT OUTER JOIN
T_AdminPayment ON T_Receipt.ReceiptNo = T_AdminPayment.ReceiptNo LEFT OUTER JOIN
T_BankTransfer ON T_Receipt.ReceiptNo = T_BankTransfer.receiptNo LEFT OUTER JOIN
T_Utilities ON T_Receipt.ReceiptNo = T_Utilities.receiptNo LEFT OUTER JOIN
T_credit ON T_Receipt.ReceiptNo = T_credit.ReceiptNo LEFT OUTER JOIN
T_cheque ON T_Receipt.ReceiptNo = T_cheque.ReceiptNo LEFT OUTER JOIN
T_InternetBilling ON T_Receipt.ReceiptNo = T_InternetBilling.ReceiptNo
GROUP BY T_Receipt.Student, T_Receipt.ReceiptNo, T_cheque.Amount, T_credit.Amount, StandingOrder.Amount, T_BankTransfer.amount, T_cash.TotalAmount,
T_AdminPayment.AmountPaid, T_InternetBilling.Total, T_Utilities.AmountPaid, T_InvoicePayment.amountPaid, T_OtherPayments.paymentAmount,
T_parkingBill.paymentAmount, T_TelephoneBills.TelephoneCredit, T_Receipt.cancelled, T_Receipt.RemittanceReceiptNo,
T_DepositPayment.[Deposit payment], T_RentPayment.AmountPayed, T_Receipt.Student
HAVING (T_Receipt.Student LIKE N'06%')

Which gives a result of:




RecNo.
30429
Cheque
250
Deposit
250


30429
679.98
250


This is fine but when I do analysis on this it appears as though the student has paid two deposit payments. I was wondering with out querying each table independently from an application if there was a criteria to specify that I only get one deposit result.
So as such say, give me all the payments but I only want one result from the other tables. I though about discrete but that wouldn't work here.

View 3 Replies View Related

Query By Year Group By Total Students Sort By Total For Each County

Jul 20, 2005

I haven't a clue how to accomplish this.All the data is in one table. The data is stored by registration dateand includes county and number of students brokne out by grade.Any help appreciated!Rob

View 4 Replies View Related

Query Help: Multiple WHERE, Multiple COUNT?

Mar 17, 2006

Howdy folks. I have a SELECT question for you. Or maybe a WHERE question. That I am not sure is part of the problem. My application is ASP.NET 2.0, and I’d like to avoid getting into stored procedures right now, if I could.
 
I am trying to summarize the order status for each customer in the database (SQL Server 2005, by the way). I want to provide two counts: the number of open jobs per customer, and the number of rush jobs per customer. Something like this:
 
CustID     CustName     JobOpen     JobRush
----------------------------------------------------------------
22            John Deere     47                3
24            MCP              32                 7
37            BlueON          6                  0
 
In my noobness, I developed this:
 
SELECT   CustID, MAX(CustName) AS CustName,
                  COUNT (*) AS JobOpen
FROM   Customers
INNER JOIN   Jobs ON JobCustID = CustID
WHERE   (JobDone = 0)
GROUP BY CustID
 
As you can see, it finds from the Jobs table all jobs that are not done (JobDone is a T/F field), joins the Jobs and Customers tables, groups by CustID, and counts the totals in each CustID group. It works great in outputting the first three columns that I am looking for.
 
But I cannot come up with a simple way to add JobRush (also a T/F field), because it needs a different WHERE clause than the one JobOpen uses. It would need
 
WHERE (JobRush = 1)
 
So maybe my question should be: how do I use multiple WHERE clauses, each with its own COUNT?
 
I did mess around with Common Table Expressions, and managed to build two CTEs (one with JobOpen results and the other with JobRush results) that I joined together. It worked in Studio Manager, but my ASP.NET page didn’t like it. I guess that means I could learn stored procedures, but wow I’d love to just have a nice complete SELECT command for my page.
 
Thanks for reading all this. Any input is greatly appreciated.
Matt
 

View 3 Replies View Related

DB Engine :: Multiple Execution Of Query Pattern Generates Same Query Plan

Oct 6, 2015

SQL Server 2012 Performance Dashboard Main advices me this:

Since the application is from a vendor and I have no control over its code, how can improve this sitation?

View 3 Replies View Related

SQL Server Admin 2014 :: Estimated Query Plan For A Stored Procedure With Multiple Query Statements

Oct 30, 2015

When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.

1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?

<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>

2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?

View 0 Replies View Related

SP To Perform Query Based On Multiple Rows From Another Query's Result Set

Nov 7, 2007

I have two tables .. in one (containing user data, lets call it u).The important fields are:u.userName, u.userID (uniqueidentifier) and u.workgroupID (uniqueidentifier)The second table (w) has fieldsw.delegateID (uniqueidentifier), w.workgroupID (uniqueidentifier) The SP takes the delegateID and I want to gather all the people from table u where any of the workgroupID's for that delegate match in w.  one delegateID may be tied to multiple workgroupID's. I know I can create a temporary table (@wgs) and do a: INSERT INTO @wgs SELECT workgroupID from w WHERE delegateID = @delegateIDthat creates a result set with all the workgroupID's .. this may be one, none or multipleI then want to get all u.userName, u.userID FROM u WHERE u.workgroupIDThis query works on an individual workgroupID (using another temp table, @users to aggregate the results was my thought, so that's included)         INSERT INTO @users             SELECT u.userName,u.userID                 FROM  tableU u                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID                WHERE u.workgroupID = @workGroupIDI'm trying to avoid looping or using a CURSOR for the performance hit (had to kick the development server after one of the cursor attempts yesterday)Essentially what I'm after is:             SELECT u.userName,u.userID
                FROM  tableU u
                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID
                WHERE u.workgroupID = (SELECT workgroupID from w WHERE delegateID = @delegateID) ... but that syntax does not work and I haven't found another work around yet.TIA!    

View 1 Replies View Related

Query Within Query - Checking For Multiple Fields

Jun 9, 2008

Hi,
I remember seeing a fancy query that checked for multiple fields in a table (I think using a select statement in the where clause but not sure), but can't remember how to do it... here is what I want to do (and maybe there is a much easier way). Thanks!

Table1
id item color
1 shoe red
2 shoe blue
3 coat green
4 coat black

Table2
item color
shoe red
coat green

I want everything in Table1 where item and color are not a match.

So my results should be:
2 shoe blue
4 coat black

I'm sorry if this is a dumb question... it's been that kind of a day!

Thanks!

View 1 Replies View Related

Query A Query With Multiple Results

Aug 22, 2005

Hi,New to .Net and SQL.  I have two tables that I have joined together.  RentalControl_Main has the rental informationd and an Adjuster ID that links to the ADjuster table and the adjusters name.  I am trying to create a report that gives the "Single" adjuster name and the totals for all of their contracts.  I have a details report that gives each contract info. for each specific adjusters rentals.  However, I want to just list the adjuster once and give all of their totals.  In my SQL statement I have all of it written out and just need to knowwhat to do in place of 'Alex Early' that will give me all of the distinct adjusters.Do I need to code this on the page with a do while loop?Appreciate any help.SELECT     SUM(dbo.RentalControl_Main.Rate) / COUNT(dbo.RentalControl_Main.Rate) AS AmtAvg, SUM(dbo.RentalControl_Main.DaysBilled)                       / COUNT(dbo.RentalControl_Main.DaysBilled) AS DayAvg, SUM(dbo.RentalControl_Main.Rate * dbo.RentalControl_Main.DaysBilled)                       / COUNT(dbo.RentalControl_Main.Rate) AS TotAvgFROM         dbo.RentalControl_Main INNER JOIN                      dbo.RentalControl_Adjuster ON dbo.RentalControl_Main.AdjusterID = dbo.RentalControl_Adjuster.AdjusterIDWHERE     (dbo.RentalControl_Adjuster.AdjusterName = 'Alex Early' AND (dbo.RentalControl_Main.DateClose IS NOT NULL) AND                       (dbo.RentalControl_Main.AgencyID = '2')

View 1 Replies View Related

Multiple WHERE's In A Query?

Nov 29, 2005

I want a query ro select the number of wins and the number of games played for a team. The pertinent columns are all in the same table and I was trying to get the information all in one query. Is something like this possible?SELECT COUNT(*) AS WinsFROM tbl_ScheduleWHERE Winner = 'IND'SELECT COUNT(*) AS GamesPlayedFROM tbl_ScheduleWHERE HomeID = 'IND' OR VisitorID = 'IND'How would I merge the two, or can I even do that?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved