In my application, when the user logs on his username and the datetime is inserted into a table named ORDER_ID
that auto increments by one. I then pull that number back out to use later using SELECT SCOPE_IDENTITY()
. At that point the user is required to answer some personal information and after answering it, the user can select some products that he wishes to return or order. Finally, once the user has made his selections all the information is saved in the ORDERS
table like this:
How would I go about writing my query so that SQL groups all orders completely and seperately?
An example:
//If connection is closed > open..if open, skip
int connOpen = 0;
if (connection.State == ConnectionState.Closed)
{
connection.Open();
connOpen = 1;
}
//Query
String query = @"SELECT * FROM Resultaat WHERE Order_ID = @ID";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.Add(new SqlParameter("ID", idInt));
//Read the result
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
String name = reader["User"].ToString();
String product = reader["Product"].ToString();
int id = (int)reader["Order_ID"];
}
// IF OPEN THEN CLOSE
if (connOpen == 1)
connection.Close();
}
cmd.Parameters.Clear();
You should have a table separately which holds data about users like User Name and stuff, and a Primary key on that table to uniquely identify each user, and you used that Primary key as a Foreign key in this Orders Table to reference Orders to each user. I really dont know what you mean by Grouping Orders "SQL groups all orders completely and seperately" .
To show data where all the orders are grouped by each users, you need to use a reporting tool sql server is for Storing Information not displaying information. You can use SSRS a free tool of Microsoft for this purpose.
You can use the following Query which return the product in comma saprated. these values is split(',') method to get user product according to order
SELECT O1.OrderId ,
Stuff((SELECT ', ' + Product
FROM tblOrder O2
WHERE O2.OrderId=O1.OrderId
FOR XML PATH('')), 1, 2, '') Product
FROM tblOrder O1
GROUP BY O1.OrderId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.