How do you write a query where only a select number of rows are returned with either the highest or lowest column value.
i.e. A report with the 5 highest salaried employees?
I have the following columns in TableA
TableA
Column1 varchar
Column2 int
Column3 bit
I am using this statement
IF Column3 = 0
SELECT Column1, Column2 FROM
TableA WHERE
Column2 > 200
ELSE
SELECT Column1, Column2 FROM
TableA WHERE
Column2 < 200
But the statment does not compile. It says Invalid Column Name 'Column3'
How do I design the database to calculate the account balance?
1) Currently I calculate the account balance from the transaction table
In my transaction table I have "description" and "amount" etc..
I would then add up all "amount" values and that would work out the user's account balance.
I showed this to my friend and he said that is not a good solution, when my database grows its going to slow down???? He said I should create separate table to store the calculated account balance. If did this, I will have to maintain two tables, and its risky, the account balance table could go out of sync.
Any suggestion?
EDIT: OPTION 2: should I add an extra column to my transaction tables "Balance".
now I do not need to go through many rows of data to perform my calculation.
Example
John buys $100 credit, he debt $60, he then adds $200 credit.
Amount $100, Balance $100.
Amount -$60, Balance $40.
Amount $200, Balance $240.
I am trying to find all deals information along with how many comments they have received. My query
select deals.*,
count(comments.comments_id) as counts
from deals left join comments on
comments.deal_id=deals.deal_id where
cancelled='N'
But now it only shows the deals that have at least one comment. What is the problem?
Hey, I am trying to create a login page that checks the username and password with the database on the server. The server is located in a different country.
This is the code I have so far:
#region Building the connection string
string Server = "XX.XXX.XX.XX, XXXX";
string Username = "_Username_";
string Password = "_Password_";
string Database = "_Database_";
string ConnectionString = "Data Source=" + Server + ";";
ConnectionString += "User ID=" + Username + ";";
ConnectionString += "Password=" + Password + ";";
ConnectionString += "Initial Catalog=" + Database;
#endregion
SqlConnection SQLConnection = new SqlConnection();
try
{
SQLConnection.ConnectionString = ConnectionString;
SQLConnection.Open();
// You can get the server version
// SQLConnection.ServerVersion
}
catch (Exception Ex)
{
// Try to close the connection
if (SQLConnection != null)
SQLConnection.Dispose();
// Create a (useful) error message
string ErrorMessage = "A error occurred while trying to connect to the server.";
ErrorMessage += Environment.NewLine;
ErrorMessage += Environment.NewLine;
ErrorMessage += Ex.Message;
// Show error message (this = the parent Form object)
MessageBox.Show(this, ErrorMessage, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Stop here
return;
}
I am getting the error message:
Non-negative number required.
Parameter name: count
I have accepted wildcards on my server and I have no idea what that error means?
Any help would be appreciated,
Thanks.
I have a DataReader and a StringBuilder (C#.NET) used in the following way;
while (reader.Read())
{
sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]);
}
Which works great for my use, but when a row is null I need it to return "null", instead of just "". What would be a good way of accomplishing that?
Suggestions are very appreciated
Select
id,
sum(amount),
vat
From transactions WHERE id=1;
Each record in this table has a vat percentage, I need to get the total amount in all records, however each amount has to be multiplied by by its vat %.
Is there away to do this without looping through all records?
I have a stupid question, I have this table :
id_product name value
1 price 10-20
1 type computer
2 price 20-30
3 price 100-200
and I want to select from this table GROUP BY id_product and ORDER BY value WHERE name='price'
how can i do this?
Thanks a lot
Pardon me for being unable to phrase the title more exact.
Basically, I have three LINQ objects linked to tables. One is Product, the other is Company and the last is a mapping table Mapping to store what Company sells which products and by which ID this Company refers to this Product.
I am now retrieving a list of products as follows:
var options = new DataLoadOptions();
options.LoadWith<Product>(p => p.Mappings);
context.LoadOptions = options;
var products = (
from p in context.Products
select new {
ProductID = p.ProductID,
//BackendProductID = p.BackendProductID,
BackendProductID = (p.Mappings.Count == 0)
? "None"
: (p.Mappings.Count > 1)
? "Multiple"
: p.Mappings.First().BackendProductID,
Description = p.Description
}
).ToList();
This does a single query retrieving the information I want. But I want to be able to move the logic behind the BackendProductID into the LINQ object so I can use the commented line instead of the annoyingly nested ternary operator statements for neatness and re-usability.
So I added the following property to the Product object:
public string BackendProductID
{
get
{
if (Mappings.Count == 0) return "None";
if (Mappings.Count > 1) return "Multiple";
return Mappings.First().BackendProductID;
}
}
The list is still the same, but it now does a query for every single Product to get it's BackendProductID. The code is neater and re-usable, but the performance now is terrible.
What I need is some kind of Expression or Delegate but I couldn't get my head around writing one. It always ended up querying for every single product, still.
Any help would be appreciated!
I am trying to construct a navigation menu using a Categories table from my db.
I have a similar layout as below in Categories table.
public List<Category> CategoryData = new List(new Category[] {
new Category{ CategoryId = 1, Name = "Fruit", ParentCategoryId = null},
new Category{ CategoryId = 2, Name = "Vegetables", ParentCategoryId = null},
new Category{ CategoryId = 3, Name = "Apples", ParentCategoryId = 1},
new Category{ CategoryId = 4, Name = "Bananas", ParentCategoryId = 1},
new Category{ CategoryId = 5, Name = "Cucumber", ParentCategoryId = 2},
new Category{ CategoryId = 6, Name = "Onions", ParentCategoryId = 2}
); }
The above should return something like
Fruit (parent)
"===Apples, Bananas (child)
Vegetables (parent)
"===Cucumber, Onions (child)
I need to be able to pass this as some kind of 'grouped' (grouped by parentid) collection to my View.
How to do this?
I haven't spent a ton of time researching this yet, mostly looking for best practices on upgrading/changing DB schemas.
We're actively developing a new product and as such we often have additions or changes to our DB schema. We also have many copies of the DB -- one for the test environment, one for the prod environment, dev environments, you name it. We don't really want to have to blow away test data every time we want to make a change to the DB.
Are there good ways of automating this or handling this? None of us have really ever had to deal with this so...
Which is better and what is the difference?
SELECT * FROM TABLE_A A WHERE A.ID IN (SELECT B.ID FROM TABLE_B B)
or
SELECT * FROM TABLE_A A, TABLE_B B WHERE A.ID = B.ID
I have one table, which has three fields and data.
Name , Top , Total
cat , 1 , 10
dog , 2 , 7
cat , 3 , 20
horse , 4 , 4
cat , 5 , 10
dog , 6 , 9
I want to select the record which has highest value of Total for each Name, so my result should be like this:
Name , Top , Total
cat , 3 , 20
horse , 4 , 4
Dog , 6 , 9
I tried group by name order by total, but it give top most record of group by result. Can anyone guide me, please?
Hi,
I am trying to pass @intDocumentNo and @intCustomerNo to a stored procedure using VBA but only @intCustomerNo is updated in dbo.tblOrderHead. I don't think the problem is with the procedure because if I enter the values manually it runs properly.
What am I doing wrong?
VBA Code:
Private Sub intCustomerNo_Click()
Dim cmdCommand As New ADODB.Command
With cmdCommand
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdStoredProc
.CommandText = "uspSelectCustomer"
'@intDocumentNo
.Parameters("@intDocumentNo").Value = Forms![frmSalesOrder].[IntOrderNo]
'@intCustomerNo
.Parameters("@intCustomerNo").Value = Me![intCustomerNo]
.Execute
End With
DoCmd.Close
Forms![frmSalesOrder].Requery
End Sub
Procedure:
UPDATE dbo.tblOrderHead
SET dbo.tblOrderHead.intCustomerNo = @intCustomerNo ,
dbo.tblOrderHead.intPaymentCode = dbo.tblCustomer.intPaymentCode,
dbo.tblOrderHead.txtDeliveryCode = dbo.tblCustomer.txtDeliveryCode,
dbo.tblOrderHead.txtRegionCode = dbo.tblCustomer.txtRegionCode,
dbo.tblOrderHead.txtCurrencyCode = dbo.tblCustomer.txtCurrencyCode,
dbo.tblOrderHead.txtLanguageCode = dbo.tblCustomer.txtLanguageCode
FROM dbo.tblOrderHead
INNER JOIN dbo.tblCustomer ON dbo.tblOrderHead.intCustomerNo =
dbo.tblCustomer.intCustomerNo
AND dbo.tblOrderHead.intOrderNo = @intDocumentNo
Hey guys, I have a program that allows me to run queries against a large database.
I have two tables that are important right now, Deposits and withdraws. Each contains a history of every user. I need to take each table, add up every deposit and withdraws (per user), then subtract the withdraws from the deposits. I then need to return every user whos result is negative (aka they withdrew more then they deposited).
Is this possible in one query?
Example:
Deposit Table:
|ID|UserName|Amount|
|1 | Use1 |100.00|
|2 | Use1 |50.00 |
|3 | Use2 |25.00 |
|4 | Use1 | 5.00 |
WithDraw Table:
|ID|UserName|Amount|
|2 | Use2 | 5.00 |
|1 | Use1 |100.00|
|4 | Use1 | 5.00 |
|3 | Use2 |25.00 |
So then the result would output:
|OverWithdrawers|
| Use2 |
Is this possible (I sure don't know how to do it)?
Thanks for any help,
Max
Hi.. I have 3 tables similar to the sctructure below
CREATE TABLE [dbo].[EmpBasic](
[EmpID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[Name] [varchar](50),
[Address] [varchar](50)
)
CREATE TABLE [dbo].[EmpProject](
[EmpID] [int] NOT NULL primary key, // referencing column with EmpBasic
[EmpProject] [varchar](50) )
CREATE TABLE [dbo].[EmpFull_Temp](
[ObjectID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[T1Name] [varchar](50) ,
[T1Address] [varchar](50) ,
[T1EmpProject] [varchar](50)
)
The EmpFull_Temp table has the records with a dummy object ID column... I want to populate the first 2 tables with the records in this table... But with EmpID as a reference between the first 2 tables.
I tried this in a stored procedure...
Create Table #IDSS (EmpID bigint, objID bigint)
Insert into EmpBasic
output Inserted.EmpID, EmpFull_Temp.ObjectID
into #IDSS
Select T1Name, T1Address from EmpFull_Temp
Where ObjectID < 106
Insert into EmpProject
Select A.EmpID, B.T1EmpProject from #IDSS as A, EmpFull_Temp as B
Where A.ObjID = B.ObjectID
But it says.. The multi-part identifier "EmpFull_Temp.ObjectID" could not be bound.
Could you please help me in achieving this...
So, I just learned about CURSORS but still don't exactly grasp them. What is the difference between a cursor and procedure or even a function?
So far from the various examples (DECLARE CURSOR ... SELECT ... FROM ...) It seems at most its a variable to hold a query. Is the data real time, or a snapshot of when the cursor was declared?
i.e.
I have a table with one row and one col with a value of 2.
I do DECLARE CURSOR ... SELECT * FROM table1
I then insert a new row with a value of 3.
When I run the cursor, would I Just get the one row from before the cursor was declared, or both rows?
Thanks
So I noticed that one of my log backups is about 1000x larger than normal. I'd like to see what is in there. Is there something I can use to read it?
Thanks!
I have used temp table in my stored procedure and unable to get the result when executing. It return result fine when running the same as query.
my query structure is something like...
ALTER PROCEDURE [dbo].[test]
as begin
SET NOCOUNT ON;
SELECT * INTO #Dates FROM Dates -- Used temp table
SET @Query = '
SELECT [Name], [HotelName], '+@Dates+'
FROM ( SELECT , HD.[Name], HD.[HotelName], HD.Price
FROM #Dates D
LEFT JOIN #HotelData HD
ON D.DateVal = HD.OccDate) T
PIVOT ( SUM(Price) FOR [Date] IN ('+@Dates+') ) AS PT'
execute(@Query)
end
Exec test -- Exectuting, I am getting message command completed successfully
Hello,
i got a MySql DB.
There is a table with products and orders.
Structure:
Products: product_id, name, manufacturers_id
Orders: orders_id, product_id, quantitiy
Now I want to get all orders (show only products where product id=1).
I tried:
SELECT
orders.orders_id,
orders.product_od
FROM products, orders
WHERE products.manufacturers_id = 1
GROUP BY orders_id
ORDER BY orders_id
But this doesnt work
Hello all,
I have some records like this:
ID Personel_Code Time
--- ------------- ------
1 0011 05:50
3 0011 20:12
4 0012 00:50
I want to have the sum of times for each person. in this example I want to have the result like this :
Personel_Code Time
------------- -----
0011 26:02
0012 00:50
Thank you.
Following is my custome cotrol grid...
public partial class LinqGrid : UserControl
{
object tmpDataTable = new object();
public LinqGrid()
{
InitializeComponent();
}
public void Bind(System.Data.Linq.Table listSource) where T : class
{
Project.dbClassesDataContext dbc = new Project.dbClassesDataContext();
tmpDataTable = listSource;
var query = (from c in listSource select c);
dgvRecords.DataSource = query.Take(10).ToList();
}
private void btnNext_Click(object sender, EventArgs e)
{
// now what i have to do here if i want next 10 records.....means how to retrive tmpDataTable object here... ??? i can't find Type of variable....?? plz help me....
}
}
A colleague is adding a bit mask to all our database tables. In theory this is so we can track certain properties of each row across the entire system. For example...
Is the row shipped with the system or added by the client once they've started using the system
Has the row been deleted from the table (soft deletes)
Is the row a default value within a set of rows
Is this a good idea? Are there other uses where this approach would be beneficial?
My preference is these properties are obviously important, and having a dedicated column for each property is justified to make what is happening clearer to fellow developers.
it puts item1 down as DESC for some reason.
edit:
$sql_result = mysql_query("SELECT post, name, trip, Thread, sticky FROM (SELECT MIN(ID) AS min_id, MAX(ID) AS max_id, MAX(Date) AS max_date FROM test_posts GROUP BY Thread ) t_min_max INNER JOIN test_posts ON test_posts.ID = t_min_max.min_id WHERE Board=".$board." ORDER BY sticky ASC, max_date DESC", $db);
http://prime.programming-designs.com/test_forum/viewboard.php?board=0&page=3
I've got a table defined as :
OrderID bigint NOT NULL,
IDA varchar(50) NULL,
IDB bigint NULL,
[ ... 50 other non relevant columns ...]
The natural primary key for this table would be (OrderID,IDA,IDB), but this it not possible because IDA and IDB can be null (they can both be null, but they are never both defined at the same time). Right now I've got a unique constraint on those 3 columns.
Now, the thing is I need a primary key to enable transactional replication, and I'm faced with two choices :
Create an identity column and use it as a primary key
Create a non-null computed column C containing either IDA or IDB or '' if both columns were null, and use (OrderID,C) as my primary key.
The second alternative seams cleaner as my PK would be meaningful, and is feasible (see msdn link), but since I've never seen this done anywhere, I was wondering if they were some cons to this approach.