How to combine results of 3 Joins? - sql

I am trying to make a table per employee that will give the information per employee that was present/absent/work from home.For that I am writing a SQL query that is fetching the records using JOINS. However, I am writing 3 Join statements that are returning me data separately. How can I write a query that will return the results of the 3 subsequent joins in one single (SELECT)query? Here are the Join statements:
Select EmployeeId, Employees.Name, COUNT(*) [Absent]
From Attendances
Left Join Employees
On Employees.EmployeeId = Attendances.EmpID And Attendances.IsAbsent = 1 and Employees.Name = 'John'
Where CAST(Attendances.InDateTime as Date) >= '2016-06-19 10:00:00.000'
Group By EmployeeId, Employees.Name
select Employees.Name, COUNT(*) [Present]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name
select Employees.Name, COUNT(*) [WorkFromHome]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name
The current output that I am getting is:
Name|Present, Name|Absent, Name|WorkFromHome
But I want it as:
Name|Present|Absent|WorkFromHome

Use Subqueries to get your desired outputs:
SELECT T1.ID,
T1.Name,
T1.[Absent],
T2.[Present],
T3.[WorkFromHome]
FROM
(
select ID, Employees.Name, COUNT(*) [Absent]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T1 JOIN
(
select ID, Employees.Name, COUNT(*) [Present]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T2 ON T1.ID = T2.ID JOIN
(
select ID, Employees.Name, COUNT(*) [WorkFromHome]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and Employees.Name='John'
Group By Employees.Name, ID
) T3 ON T2.ID = T3.ID;

You can use UNION or UNION ALL. For Example
SELECT * FROM TABLE WHERE NAME = 'Mohit'
UNION ALL
SELECT * FROM TABLE WHERE NAME = 'Jhon'
UNION ALL
SELECT * FROM TABLE WHERE NAME = 'Jeni'
UNION ALL will return unique records. However UNION will return all the record.

Use UNION ALL to get combined data like this
select Employees.Name, 'A' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name
UNION ALL
select Employees.Name, 'P' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsAbsent = 0
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name
UNION ALL
select Employees.Name, 'WFH' Attendance, COUNT(*) [Count]
from Employees
Inner Join Attendances
On Employees.UserId = Attendances.EmpID and Attendances.IsWorkFromHome = 1
Where CAST(Attendances.InDateTime as Date) >= '2017-06-19 10:00:00.000' and
Employees.Name='John'
Group By Employees.Name

Related

UNION on 2 joined queries

I have 2 working queries that are joined by subselects using WITH in DB2.
They each work separately but I can't seem to find the best way to properly combine or union them.
The first query:
with c as(
select
employee,
sum(salesPrice) as priorSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
and g.details = 'CategoryOne'
group by employee
), d as(
select
employee,
sum(salesPrice) as priorTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
group by employee
)
Select ifnull(c.employee,d.employee) as employee
,c.priorSpecifics
,d.priorTotals
,cast(Round((DEC(c.priorSpecifics,12,2)/DEC(d.priorTotals,12,2)) * 100,2) as decimal(12,2)) as priorPercent
from c full join d ON (c.employee = d.employee);
Returns 4 columns
and the 2nd query
with c as(
select
employee,
sum(salesPrice) as currentSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
and g.details = 'CategoryOne'
group by employee
), d as(
select
employee,
sum(salesPrice) as currentTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
group by employee
)
Select ifnull(c.employee,d.employee) as employee
,c.currentSpecifics
,d.currentTotals
,cast(Round((DEC(c.currentSpecifics,12,2)/DEC(d.currentTotals,12,2)) * 100,2) as decimal(12,2)) as currentPercent
from c full join d ON (c.employee = d.employee);
Returns 4 as well. The field employee is the only thing that is shared between all.
How can I combine this into one query to get one employee column and then all of my sum/percent columns following?
I think you can do everything you want with conditional aggregation:
select employee,
sum(case when d.newDate between '2018-01-01' and '2018-01-31' and g.details = 'CategoryOne' then salesPrice end) as priorSpecifics,
sum(case when d.newDate between '2019-01-01' and '2019-01-31' and g.details = 'CategoryOne' then salesPrice end) as currentSpecifics,
sum(case when d.newDate between '2018-01-01' and '2018-01-31' then salesPrice end) as priorTotals,
sum(case when d.newDate between '2019-01-01' and '2019-01-31' then salesPrice end) as currentTotals
from schema1.orders g inner join
dateSchema.dates d
on g.dateField = d.dateField
group by employee;
I'll let you fill in with the additional calculations.
If all the above queries are working then you already have everything you need.
You must combine from the 1st group, the first 2 to make the prior query, then
from the 2nd group to make the cur query
and finally join the prior query to the cur query:
with
c as(
select
employee,
sum(salesPrice) as priorSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
and g.details = 'CategoryOne'
group by employee
),
d as(
select
employee,
sum(salesPrice) as priorTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2018-01-01' and '2018-01-31'
group by employee
),
prior as (
Select ifnull(c.employee,d.employee) as employee
,c.priorSpecifics
,d.priorTotals
,cast(Round((DEC(c.priorSpecifics,12,2)/DEC(d.priorTotals,12,2)) * 100,2) as decimal(12,2)) as priorPercent
from c full join d ON (c.employee = d.employee)
),
e as(
select
employee,
sum(salesPrice) as currentSpecifics
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
and g.details = 'CategoryOne'
group by employee
),
f as(
select
employee,
sum(salesPrice) as currentTotals
from schema1.orders g
inner join dateSchema.dates d
on g.dateField = d.dateField
where d.newDate between '2019-01-01' and '2019-01-31'
group by employee
),
cur as (
Select ifnull(e.employee,f.employee) as employee
,e.currentSpecifics
,f.currentTotals
,cast(Round((DEC(e.currentSpecifics,12,2)/DEC(f.currentTotals,12,2)) * 100,2) as decimal(12,2)) as currentPercent
from e full join f ON (e.employee = f.employee)
)
Select ifnull(p.employee, c.employee) as employee
,p.priorSpecifics
,p.priorTotals
,p.priorPercent
,c.currentSpecifics
,c.currentTotals
,c.currentPercent
from prior p full join cur c ON (c.employee = c.employee);

SQL Inner join group... missing expression

I have following query, which works fine:
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE
exists_db = 0
and is_checked = 1
and batch_counter > 0
and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock
FROM koll_customer_export) e
ON e.id = c.id
My requirement is to add another column 'YellowCategory'. For that I tried to change the query to following:
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE
exists_db = 0
and is_checked = 1
and batch_counter > 0
and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock, COUNT(b.batch_counter) AS YellowCategory,
FROM koll_customer_export
WHERE to_date(created_date,'DD.MM.RRRR HH24:MI:SS') < to_date(sysdate-time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY b.batch_counter) e
ON e.id = c.id
But then I get "missing expression" error. I guess in last INNER JOIN. Don't know where is the problem... Any help?
Update
With following query, I get b.batch_counter invalid identifier error now.
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount,
b.InvoiceCount, e.time_of_delivery, e.time_of_delivery_mail,
e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c
INNER JOIN (
SELECT batch_prefix, batch_counter, COUNT(*) AS BatchCount,
SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE exists_db = 0 and is_checked = 1
and batch_counter > 0 and trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix
) b
ON b.batch_prefix=c.customer_prefix
INNER JOIN (
SELECT id, time_of_delivery, time_of_delivery_mail,
time_of_delivery_clock,
COUNT(b.batch_counter) AS YellowCategory
FROM koll_customer_export
WHERE to_date(created_date,'DD.MM.RRRR HH24:MI:SS')
< to_date(sysdate- time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY b.batch_counter
) e
ON e.id = c.id
Is this the query you want?
SELECT c.id, c.customer_name, b.batch_prefix, b.BatchCount, b.InvoiceCount,
e.time_of_delivery, e.time_of_delivery_mail, e.time_of_delivery_clock, e.YellowCategory
FROM koll_customers c INNER JOIN
(SELECT batch_prefix, COUNT(*) AS BatchCount, SUM (batch_counter) AS InvoiceCount
FROM koll_batchlogs
WHERE exists_db = 0 and is_checked = 1 and batch_counter > 0 and
trunc(created_date) > trunc(sysdate-7)
GROUP BY batch_prefix
) b
ON b.batch_prefix = c.customer_prefix INNER JOIN
(SELECT id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock,
COUNT(*) AS YellowCategory,
FROM koll_customer_export
WHERE to_date(created_date, 'DD.MM.RRRR HH24:MI:SS') < to_date(sysdate-time_of_delivery,'DD.MM.RRRR HH24:MI:SS')
GROUP BY id, time_of_delivery, time_of_delivery_mail, time_of_delivery_clock
) e
ON e.id = c.id;
It is impossible for me to say if this is what you really need. But I think the query will at least compile so you can run it.. The where clause in the e subquery looks really strange. Why would you be converting a date column into a date column using to_date()?
You typed one comma too much at the end of the SELECT list inside the last INNER JOIN.

How to insert into one table from multiple table while using UNION

I have the following query which queries different table and uses the UNION operator to display a set of data:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
Which displays the following:
TYPE TOTAL
CDS 45
DEA 56
INFECTION 67
LICENSE 41
I would like to insert the data into a table that I can import as a DataSet in my SSRS report. How can I achieve it?
I tried doing the following:
-----TOTAL COUNT OF ACTIVE DEA----- DEA
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectinsta d inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectinsta
group by fk1665) n on d.objectid = n.newobjectid where attr1671 = 'DEA' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
-----TOTAL COUNT OF ACTIVE LICENSES----- LICENSE
UNION
select 'LICENSE' as 'TYPE', count(*) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobjectin t inner join (select fk1656, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobjectin
group by fk1656) c on t.objectid = c.newobjectid where cast(attr1660 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL INFECTION CERTIFICATIONS ACTIVE----- INFECTION
UNION
select 'INFECTION' as 'TYPE', count(*) 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobject z inner join (select fk1676, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobject
group by fk1676) h on z.objectid = h.newobjectid where cast(attr1680 as date) > cast(getdate()+30 as date) and activestatus = 0
-----TOTAL COUNT OF ACTIVE CDS----- CDS
UNION
select attr1671 as 'TYPE', count(attr1668) as 'TOTAL'
INTO [MYDB].[DBO].[myT] --on first run and then comment
from [MyServer].[DBOTYPE].instance.rmobje k inner join (select fk1665, max(objectid) 'newobjectid'
from [MyServer].[DBOTYPE].instance.rmobje
group by fk1665) l on k.objectid = l.newobjectid where attr1671 = 'CDS' and cast(attr1668 as date) > cast(getdate()+30 as date) and activestatus = 0
group by attr1671
But that didn't work. Please help...
This is the error I get:
Msg 196, Level 15, State 1, Line 2
SELECT INTO must be the first query in a statement containing a UNION, INTERSECT or EXCEPT operator.
You can try wrapping the whole thing as a subselect:
select *
into <whatever>
from (<your query here>
) t;
Try this :
With Emp_CTE (Employee,Count)
AS
(
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'V%'
group by FirstName
union
Select Firstname as Employee , Count(*) as Count from Employee
where FirstName like 'M%'
group by FirstName
)
Select * into dbo.EmployeeCount from Emp_CTE;

inner join results of "with" clause

I have 2 with clauses like this:
WITH T
AS (SELECT tfsp.SubmissionID,
tfsp.Amount,
tfsp.campaignID,
cc.Name
FROM tbl_FormSubmissions_PaymentsMade tfspm
INNER JOIN tbl_FormSubmissions_Payment tfsp
ON tfspm.SubmissionID = tfsp.SubmissionID
INNER JOIN tbl_CurrentCampaigns cc
ON tfsp.CampaignID = cc.ID
WHERE tfspm.isApproved = 'True'
AND tfspm.PaymentOn >= '2013-05-01 12:00:00.000' AND tfspm.PaymentOn <= '2013-05-07 12:00:00.000')
SELECT SUM(Amount) AS TotalAmount,
campaignID,
Name
FROM T
GROUP BY campaignID,
Name;
and also:
WITH T1
AS (SELECT tfsp.SubmissionID,
tfsp.Amount,
tfsp.campaignID,
cc.Name
FROM tbl_FormSubmissions_PaymentsMade tfspm
INNER JOIN tbl_FormSubmissions_Payment tfsp
ON tfspm.SubmissionID = tfsp.SubmissionID
INNER JOIN tbl_CurrentCampaigns cc
ON tfsp.CampaignID = cc.ID
WHERE tfspm.isApproved = 'True'
AND tfspm.PaymentOn >= '2013-05-08 12:00:00.000' AND tfspm.PaymentOn <= '2013-05-14 12:00:00.000')
SELECT SUM(Amount) AS TotalAmount,
campaignID,
Name
FROM T1
GROUP BY campaignID,
Name;
Now I want to join the results of the both of the outputs. How can I do it?
Edited: Added the <= cluase also.
Reults from my first T:
Amount-----ID----Name
1000----- 2-----Annual Fund
83--------1-----Athletics Fund
300-------3-------Library Fund
Results from my T2
850-----2-------Annual Fund
370-----4-------Other
The output i require:
1800-----2------Annual Fund
83-------1------Athletics Fund
300------3-------Library Fund
370------4-----Other
You don't need a join. You can use
SELECT SUM(tfspm.PaymentOn) AS Amount,
tfsp.campaignID,
cc.Name
FROM tbl_FormSubmissions_PaymentsMade tfspm
INNER JOIN tbl_FormSubmissions_Payment tfsp
ON tfspm.SubmissionID = tfsp.SubmissionID
INNER JOIN tbl_CurrentCampaigns cc
ON tfsp.CampaignID = cc.ID
WHERE tfspm.isApproved = 'True'
AND ( tfspm.PaymentOn BETWEEN '2013-05-01 12:00:00.000'
AND '2013-05-07 12:00:00.000'
OR tfspm.PaymentOn BETWEEN '2013-05-08 12:00:00.000'
AND '2013-05-14 12:00:00.000' )
GROUP BY tfsp.campaignID,
cc.Name
If I am right, after a WITH-clause you have to immediatly select the results of that afterwards. So IMHO your best try to achieve joining the both would be to save each of them into a temporary table and then join the contents of those two together.
UPDATE: after re-reading your question I realized that you probably don't want a (SQL-) join but just your 2 results packed together in one, so you could easily achieve that with what I descibed above, just select the contents of both temporary tables and put a UNION inbetween them.
I was thinking it wrongly. Thanks for the help. This is how i achieved what exactly i want:
WITH
T AS (
SELECT tfsp.SubmissionID , Amount1 =
CASE
WHEN tfspm.PaymentOn >= '2013-01-10 11:34:54.000' AND tfspm.PaymentOn <= '2013-04-10 11:34:54.000' THEN tfsp.Amount
END
, Amount2 =
CASE
WHEN tfspm.PaymentOn >= '2013-05-01 11:34:54.000' AND tfspm.PaymentOn <= '2013-05-23 11:34:54.000' THEN tfsp.Amount
END
, tfsp.campaignID , cc.Name FROM tbl_FormSubmissions_PaymentsMade tfspm
INNER JOIN tbl_FormSubmissions_Payment tfsp ON tfspm.SubmissionID = tfsp.SubmissionID
INNER JOIN tbl_CurrentCampaigns cc ON tfsp.CampaignID = cc.ID
WHERE tfspm.isApproved = 'True'
)
SELECT ISNULL(SUM(Amount1),0) AS TotalAmount1, ISNULL(SUM(Amount2),0) AS TotalAmount2, campaignID , Name FROM T GROUP BY campaignID, Name;

search between date with query have calculation and counter

Hello everyone i have big query to calculation and counter by clinic ID
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService, SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept
FROM ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc WHERE (Status = 1)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write) AS cr ON
cs.ID = cr.Clinic_Service_ID INNER JOIN
(SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name) AS nc ON cs.Clinic_ID = c.ID
GROUP BY nc.Name, nc.ID
it is true query but i want add between date
AND tc.Date_Write BETWEEN tc.Date_Write AND tc.Date_Write
in subquery
Select tc.Date_Write
Group by tc.Date_Write
in main query
like this
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE (Status = 1) AND tc.Date_Write BETWEEN tc.Date_Write AND tc.Date_Write
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
it is false query why because it is display every receipt but i want display
1 - TotalPriceService
2 - TotalPaid
3 - TotalInsurance
4 - TotalCounterReceipt
5 - FromDate
6 - ToDate
the true query that returns calculation and counter i want add search by date i know the second query it is wrong but i want search by date BETWEEN tc.Date_Write FROMDATE AND TODATE how do this thank you for help me
Your BETWEEN clause checks whether a date is between itself. This will return true for every record.
To use BETWEEN correctly, you need to supply two other dates. This query seems like a candidate for a stored procedure that has two date parameters, a "from" date and a "to" date, like this:
CREATE PROCEDURE usp_GetClinicStats(
#FromDate DATETIME,
#ToDate DATETIME
)
AS
BEGIN
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE Status = 1
AND tc.Date_Write BETWEEN CONVERT(VARCHAR, #FromDate, 111) AND CONVERT(VARCHAR, #ToDate, 111)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
END
CREATE PROCEDURE usp_GetClinicStats(
#FromDate DATETIME,
#ToDate DATETIME
)
AS
BEGIN
SELECT nc.ID AS ClinicID, nc.Name AS ClinicName,
SUM(cr.CountRecept * cs.Price) AS TotalPriceService,
SUM(cr.TotalPaid) AS TotalPaid,
SUM(cs.Price * cr.Company_Percentage / 100) AS TotalInsurance,
SUM(cr.CountRecept) AS TotalCountRecept, cr.Date_Write
FROM dbo.ClinicsServices AS cs INNER JOIN
(SELECT tc.Date_Write, COUNT(ID) AS CountRecept, Clinic_Service_ID,
Company_Percentage, Company_ID, SUM(Paid_Patient) AS TotalPaid
FROM dbo.TicketsClinics AS tc
WHERE (Status = 1) AND convert(varchar,tc.Date_Write,111) BETWEEN
convert(varchar,#FromDate,111) AND convert(varchar,#ToDate,111)
GROUP BY Clinic_Service_ID, Company_Percentage, Company_ID, tc.Date_Write)
AS cr ON cs.ID = cr.Clinic_Service_ID
INNER JOIN (SELECT ID, NAME FROM dbo.Clinics AS c GROUP BY ID, Name)
AS nc ON cs.Clinic_ID = nc.ID
GROUP BY nc.Name, nc.ID, cr.Date_Write
END