SELECT
StaffID,
SUM(Treatment.TreatmentPrice) AS TotalStaffRevenue,
SUM(Treatment.TreatmentPrice) * ? AS Commission
FROM
Treatment
INNER JOIN
Appointment ON Appointment.TreatmentID = Treatment.TreatmentID
WHERE
AppointmentDate >= '2018/05/11'
AND AppointmentDate <= '2018/05/12'
GROUP BY
staffid WITH ROLLUP
CREATE TABLE Staff (
StaffID int IDENTITY NOT NULL,
Forename varchar(20) NOT NULL,
Surname varchar(20) NOT NULL,
MobileNumber varchar(11) NOT NULL,
EmailAddress varchar(20) NULL,
PostCode varchar(8) NULL,
HouseNumber varchar(4) NULL,
Commission decimal(6,2) NOT NULL,
PRIMARY KEY(StaffID)
);
GO
CREATE TABLE Treatment (
TreatmentID int identity NOT NULL,
TreatmentName varchar(20) NOT NULL,
TreatmentPrice money NOT NULL,
CategoryID int NOT NULL,
TreatmentDescription varchar(40) NOT NULL,
PRIMARY KEY(TreatmentID, CategoryID)
);
GO
CREATE TABLE Appointment (
AppointmentID int IDENTITY NOT NULL,
StaffID int NOT NULL,
TreatmentID int NOT NULL,
CustomerID int NOT NULL,
AppointmentDate date NOT NULL,
AppointmentTime time(0) NOT NULL,
PRIMARY KEY (AppointmentID, StaffID, CustomerID, TreatmentID)
);
I want the ability to multiply the sum of TreatmentPrice by Staff.Commission. I have tried INNER JOINing with Staff but it still doesn't work also how would I implement this in the front end (c#) would i use a for each loop, this would then populate a datagrid.
How did you get Staff.Commission without any join to the Staff table in your query?
Try
SELECT
Staff.StaffID,
SUM(Treatment.TreatmentPrice) AS TotalStaffRevenue,
SUM(Treatment.TreatmentPrice)*Commission AS Commission
FROM
Treatment
INNER JOIN
Appointment ON Appointment.TreatmentID = Treatment.TreatmentID
inner join Staff on Appointment.StaffID=Staff.StaffID
WHERE
AppointmentDate >= '2018/05/11'
AND AppointmentDate <= '2018/05/12'
GROUP BY
Staff.StaffID,Commission WITH ROLLUP
Related
I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
I have a table for comments where I can add records in n levels, it means that I can have a comment that it is in the nth level of reply of a comment.
My problem is that how can I dynamically select n levels of comment using linq?
For example I want comments reply for 5th level or 2nd or nth.
Here is my table
public partial class {
public Comment()
{
this.Comments1 = new HashSet<Comment>();
}
public int CommentId { get; set; }
public Nullable<int> ParentId { get; set; }
public string Title { get; set; }
public virtual ICollection<Comment> Comments1 { get; set; }
public virtual Comment Comment1 { get; set; }
}
till now i use linq and call this function in sql-server to get all the children :
[DbFunction("Ents", "cmTree")]
public virtual IQueryable<ContentComment> cmTree(string topLevelComments)
{
var topLevelCommentsParameter = topLevelComments != null ?
new ObjectParameter("topLevelComments", topLevelComments) :
new ObjectParameter("topLevelComments", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<ContentComment>("[Entities].[cmTree](#topLevelComments)", topLevelCommentsParameter);
}
an then in sql-server:
ALTER FUNCTION [dbo].[cmTree]
(
-- Table types seems goods here.
-- but in application-level, linq to sql technology dose not support table types.
-- TupleValue type can user for future use.
#topLevelComments NVARCHAR(max)
)
RETURNS #resultTable TABLE (
[Id] [bigint] primary KEY NOT NULL,
[AuthorUserId] [int] NULL,
[AuthorName] [nvarchar](128) NULL,
[AuthorEmail] [nvarchar](256) NULL,
[AuthorUrl] [nvarchar](512) NULL,
[AuthorIp] [nvarchar](100) NULL,
[InsertDateTime] [datetime] NOT NULL,
[BodyContent] [nvarchar](max) NOT NULL,
[IsApproved] [bit] NOT NULL,
[IsAlertable] [bit] NOT NULL,
[ContentId] [bigint] NOT NULL,
[ParentCommentId] [bigint] NULL,
[VerifierUserID] [int] NULL,
[VerifyDateTime] [datetime] NULL,
[Status] [bit] NOT NULL,
[LastModifierUserId] [int] NULL,
[LastModifiedDateTime] [datetime] NULL
)
AS
BEGIN
with CommentTableExpression As (
-- Anchor entities
select rC.Id, rc.AuthorUserId, rc.AuthorName, rc.[AuthorEmail], rc.[AuthorUrl], rc.[AuthorIp], rc.[InsertDateTime], rc.[BodyContent], rc.[IsApproved], rc.[IsAlertable], rc.[ContentId], rc.[ParentCommentId], rc.[VerifierUserID], rc.[VerifyDateTime], rc.[Status], rc.[LastModifierUserId], rc.[LastModifiedDateTime]
from dbo.ContentComments as rC
WHERE rc.ParentCommentId IN (SELECT * FROM dbo.CSVToTable(#topLevelComments))
union all
-- Recursive query execution
select child.Id, child.AuthorUserId, child.AuthorName, child.[AuthorEmail], child.[AuthorUrl], child.[AuthorIp], child.[InsertDateTime], child.[BodyContent], child.[IsApproved], child.[IsAlertable], child.[ContentId], child.[ParentCommentId], child.[VerifierUserID], child.[VerifyDateTime], child.[Status], child.[LastModifierUserId], child.[LastModifiedDateTime]
from dbo.ContentComments as child
inner join CommentTableExpression as t_Comment
on child.ParentCommentId = t_Comment.Id
where child.ParentCommentId is not NULL) -- commente contet=nt budan barasi shavad.
INSERT #resultTable Select * from CommentTableExpression
RETURN
END
Any help would be appreciated..
It will be better to manage one more field in the table called "ChildLevel" and add reply level in that field.
But if you want to use same structure and want to manage then below linq will get 5th level children
var rec = dt.Comments().Where(t => t.Comment1 != null
&& t.Comment1.Comment1 != null
&& t.Comment1.Comment1.Comment1 != null
&& t.Comment1.Comment1.Comment1.Comment1 != null );
I am creating tables in Sql Management Studio 2012 using SQL. How do I make fields or columns with names that are already defined in Sql Server e.g User_ID, User_Name. I want to use them as fields in my tables.
Table definition from Duplicate Post:
create table Ticket(
Ticket_Id varchar(10) not null,
TicketType_Id varchar(3) not null,
Ticket_PurchaseDate DateTime null,
LottoDraw_Id int null,
User_Id int null,
Ticket_IsWinner bit null
Primary Key(Ticket_Id,TicketType_Id)
)
Warp the column name like in brackets [ ] ... such as
create table Ticket(
Ticket_Id varchar(10) not null,
TicketType_Id varchar(3) not null,
Ticket_PurchaseDate DateTime null,
LottoDraw_Id int null,
[User_Id] int null,
Ticket_IsWinner bit null
Primary Key(Ticket_Id,TicketType_Id)
)
I have a table Invoices
Structure of Invoices
CREATE TABLE Invoices (
Id int NOT NULL IDENTITY (1, 1),
Depot nvarchar(100) NOT NULL,
InvoiceNo nvarchar(100) NOT NULL,
InvoiceDate datetime NOT NULL,
Licencee nvarchar(255) NOT NULL,
Outlet nvarchar(1024) NOT NULL,
SerialNo int NOT NULL,
ProductName nvarchar(500) NOT NULL,
Size int NOT NULL,
[Case] int NOT NULL,
BeverageSegment nvarchar(100),
/* Keys */
PRIMARY KEY (Id)
)
GO
CREATE INDEX Invoices_BeverageSegment
ON Invoices
(BeverageSegment)
GO
CREATE INDEX Invoices_InvoiceId
ON Invoices
(InvoiceNo)
GO
I have to query for Total Sales for a particular Depot, for a Product on Date, i have approx 1,35,850 in the Table, the Query is taking 47 minute.
I do not have much expertise in database system, i have checked for Query Optimization for SqlCe but none of them helps in this condition.
My query :
SELECT
Depot,
InvoiceDate,
ProductName,
Size,
SUM([Case]) as Cases
FROM Invoices
GROUP BY
Depot,
InvoiceDate,
ProductName,
Size
Creating a non clustered index on all the four columns Depot, InvoiceDate, ProductName, Size will increase the performance.
Create NonClustered Index Index_Name
on
Invoices ( Depot, InvoiceDate, ProductName, Size)
I have created the EF model and then in a Class I have written the following Code to retrieve the value form the DataBase. And store the value in another Table. But it gives me the Error "DATAREADER IS INCompatable" as explained Below..
EmpRole empr = new EmpRole();
empr.EmpId = strEmpId;
string str="select RoleId from RoleName where roleName like '"+strDesignation+"'";
var context= DbAccess.Data.ExecuteStoreQuery<RoleName>(str, null); //Here Showing Error
empr.RoleId = Convert.ToInt16(context);
DbAccess.Data.EmpRoles.AddObject(empr);
DbAccess.Commit();
It's showing the error like:
DataTables were:
CREATE TABLE [dbo].[RoleName](
[SNo] [int] IDENTITY(1,1) NOT NULL,
[RoleId] [smallint] NOT NULL,
[RoleName] [varchar](50) NULL,
CONSTRAINT [PK_RoleName] PRIMARY KEY CLUSTERED
(
[RoleId] ASC
)
CREATE TABLE [dbo].[EmpRoles](
[Sno] [int] IDENTITY(1,1) NOT NULL,
[EmpId] [varchar](8) NOT NULL,
[RoleId] [smallint] NOT NULL,
[ReportingToId] [varchar](8) NULL,
CONSTRAINT [PK_EmpRoles] PRIMARY KEY CLUSTERED
(
[Sno] ASC
)
The data reader is incompatible with the specified 'MyOrgDBModel.RoleName'. A member of the type, 'SNo', does not have a corresponding column in the data reader with the same name.
Please tell me the reasons what to do to execute the sqlQuery.
This is because you are not selecting the SNo column in your select query. As you are populating in RoleName and it has property SNo column should be present in data reader. If you just want the RoleId to be in query then create new type with one property RoleId and use this. Create new type like below
public class CustomRoleName
{
int RoleId { get; set; }
}
Now change your code as follow
EmpRole empr = new EmpRole();
empr.EmpId = strEmpId;
string str="select RoleId from RoleName where roleName like '"+strDesignation+"'";
foreach(CustomRoleName rn in DbAccess.Data.ExecuteStoreQuery<CustomRoleName>(str))
{
empr.RoleId = rn.RoleId ;
DbAccess.Data.EmpRoles.AddObject(empr);
DbAccess.Commit();
break;
}