search between date with query have calculation and counter - sql-server-2005

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

Related

0 Results Effecting Entire Query

I was wondering if there is a way to make a results from a JOIN of a subquery result a predefined entry.
The query below pulls in the MAX(ReceiveDate) for the uniqueID JobNo. However, if nothing has been received the entire result will not show up. There are several other joins that could have data.
--***SUB QUERY (Receiver)
JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo
The query will ultimately pull in data from purchase orders, result the most recent date, and the receiver with its most recent date based on the JobNo.
If nothing is received then result 'Whatever' or NULL. Anything.
The entire query is below:
DECLARE #now DATETIME
DECLARE #90daysago DATETIME
SET #now = GETDATE()
SET #90daysago = DATEADD(day, -90, #now)
;with cte as
(
SELECT
o.PartNo,
o.JobNo,
ord.DateEnt as oDateEnt,
por.MAXPONum,
po.DateEnt as poDateEnt,
tt.MAXtt,
r.ReceiveDate,
CASE
WHEN po.DateEnt >= r.ReceiveDate AND po.DateEnt >= tt.MAXtt THEN cast(po.DateEnt as DATE)
WHEN r.ReceiveDate >= po.DateEnt AND r.ReceiveDate >= tt.MAXtt THEN cast(r.ReceiveDate as DATE)
WHEN tt.MAXtt >= po.DateEnt AND tt.MAXtt >= r.ReceiveDate THEN cast(tt.MAXtt as DATE)
ELSE po.DateEnt
END AS MostRecentDate,
POProrate.TotalCost,
WIPProrate.WIPProrateCost,
(POProrate.TotalCost+WIPProrate.WIPProrateCost) as ProratedCost,
(ROUND(cast((o.QtyToMake - o.QtyShipped2Stock) as FLOAT)/o.QtyToMake,3))*(POProrate.TotalCost+WIPProrate.WIPProrateCost) as TotalProratedCost,
ROW_NUMBER() OVER(PARTITION BY o.JobNo ORDER BY tt.MAXtt DESC) as RowNum
FROM
--***MAIN QUERY (OrderDet)***
OrderDet as o
--***SUB QUERY (Order)***
JOIN
(
SELECT
cast(DateEnt as DATE) as DateEnt,
OrderNo
FROM
Orders
) ord
ON ord.OrderNo = o.OrderNo
--***SUB QUERY (POReleases)***
JOIN
(
SELECT
MAX(PONum) as MAXPONum,
JobNo
FROM
POReleases
GROUP BY
JobNo
) por
ON por.JobNo = o.JobNo
--***SUB QUERY (PO)***
JOIN
(
SELECT
PONum,
cast(DateEnt as DATE) as DateEnt
FROM
PO
) po
ON po.PONum = por.MAXPONum
--***SUB QUERY (TimeTicketDet)
JOIN
(
SELECT MAX(CAST(TicketDate as DATE)) as MaxTT,
JobNo
FROM TimeTicketDet as tt
GROUP BY JobNo
) tt
ON tt.JobNo = o.JobNo
--***SUB QUERY (Receiver)
JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo
--***SUB QUERY (POProrate)***
JOIN
(
SELECT
j.JobNo,
SUM(j.TotalCost) as TotalCost
FROM
(
SELECT
por.JobNo,
CASE
WHEN pod.Unit = 'LOT' THEN SUM(pod.UnitCost*1)
ELSE SUM(por.Qty*pod.UnitCost)
END as TotalCost
FROM
PODet as pod
INNER JOIN
POReleases as por ON pod.PONum = por.PONum and pod.partno=por.partno
GROUP BY por.JobNo, pod.Unit
) j
GROUP BY j.JobNo
) POProrate
ON o.JobNo = POProrate.JobNo
--***SUB QUERY (WIPProrate)***
JOIN
(
SELECT
j.JobNo,
SUM(j.ProratedCost) as WIPProrateCost
FROM
(
SELECT
tt.StepNo,
tt.JobNo,
tt.ActualPayRate,
tt.BurdenRate,
tt.CycleTime,
tt.SetupTime,
tt.CycleTime + tt.SetupTime as TotalTime,
(tt.CycleTime + tt.SetupTime) * tt.ActualPayRate as LaborCost,
(tt.CycleTime + tt.SetupTime) * tt.BurdenRate as BurdenCost,
((tt.CycleTime + tt.SetupTime) * tt.ActualPayRate) + ((tt.CycleTime + tt.SetupTime) * tt.BurdenRate) as ProratedCost
FROM
TimeTicketDet as tt
) j
GROUP BY j.JobNo
) WIPProrate
ON WIPProrate.JobNo = o.JobNo
WHERE
o.Status = 'Open'
AND o.JobNo <> ''
AND ord.DateEnt <= #90daysago
AND po.DateEnt <= #90daysago
AND tt.MAXtt <= #90daysago
AND r.ReceiveDate <= #90daysago
)
SELECT *
FROM cte
WHERE
RowNum = 1
Your sub query needs to be a LEFT JOIN instead of a regular JOIN which will allow it to include results if present and NULL otherwise.
--***SUB QUERY (Receiver)
LEFT JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo

Opening and Closing Inventory between Dates in SQL Server

I have four tables
tblDate (Date, Year, Month, Day)
tblItems (ItemID, ItemName)
tblItemReceived (Date, ItemID, Quantity)
tblItemUsed (Date, ItemID, Quantity)
I want report with:
Date, ItemName, Opening Quantity, Received Quantity, Used Quantity, Balance
I cannot get the results in date when no receiving.
Tables
Result
i applied, with different table (original)
select *
FROM (SELECT ivt.ITEMID AS rItemID, ivt.NAMEALIAS as rItemName, iUOM, YearRec, MonthRec, OpeningStock, RecMaterial
FROM INVENTTABLE ivt LEFT JOIN
(SELECT in1.YearRec, in1.MonthRec, in1.rItemID, iUOM, ISNULL(in1.OpeningStock, 0) AS OpeningStock, ISNULL(in1.ReceivedMaterial,0) AS RecMaterial
FROM (SELECT Year(ReceivedDate) AS YearRec, Month(ReceivedDate) AS MonthRec, rItemID, iUOM, MIN(OpenQty) AS OpeningStock, SUM(RecQty) ReceivedMaterial
FROM ( SELECT rItemID, ReceivedDate, iUOM, SUM(ReceivedQty) AS RecQty, (SELECT SUM(q.QTY) FROM VENDPACKINGSLIPTRANS q WHERE q.INVENTDATE < rm.ReceivedDate AND q.ITEMID = rm.rItemID) AS OpenQty
FROM ( SELECT vp.ITEMID AS rItemID, vp.INVENTDATE as ReceivedDate, vp.PURCHUNIT as iUOM, SUM(vp.QTY) as ReceivedQty FROM VENDPACKINGSLIPTRANS AS vp GROUP BY vp.ITEMID, vp.INVENTDATE,vp.PURCHUNIT) rm
GROUP BY rItemID, ReceivedDate,iUOM) inv
GROUP BY Year(ReceivedDate), Month(ReceivedDate), rItemID, iUOM) in1 WHERE (in1.YearRec= 2016 AND in1.MonthRec = 06)
) iv2
ON ivt.ITEMID = iv2.rITemID) le
LEFT JOIN
(SELECT c1.YearConsume, c1.MonthConsume, c1.cItemID, c1.BOM_Unit, MIN(c1.BOM_Consumption_Prev) as PrevConsump, SUM(c1.BOM_ConsumptionQty_Curr) AS TotalConsump
FROM ( SELECT Year(DateConsume) AS YearConsume, Month(DateConsume) AS MonthConsume, ItemID as cITemID, BOM_Unit, ISNULL(BOM_Consumption_Open,0) AS BOM_Consumption_Prev, SUM(BOM_ConsumptionQty) AS BOM_ConsumptionQty_Curr
FROM ( SELECT DateConsume, ItemID, BOM_Unit, SUM(BOM_Consumption) AS BOM_ConsumptionQty,
( SELECT SUM(bc.BOM_Consumption) FROM (SELECT (b.TRANSDATE) AS DateConsume, b.ITEMID AS cItemID, b.BOMUNITID BOM_Unit, SUM(b.BOMCONSUMP) AS BOM_Consumption FROM PRODJOURNALBOM b GROUP BY b.TRANSDATE, b.ITEMID, b.BOMUNITID) bc
WHERE (bc.DateConsume < aa.DateConsume) AND bc.cItemID = aa.ItemID) AS BOM_Consumption_Open
FROM (SELECT (b.TRANSDATE) AS DateConsume, b.ITEMID AS ItemID, b.BOMUNITID BOM_Unit, SUM(b.BOMCONSUMP) AS BOM_Consumption FROM PRODJOURNALBOM b GROUP BY b.TRANSDATE, b.ITEMID, b.BOMUNITID) aa
GROUP BY DateConsume, ItemID, BOM_Unit) cc
GROUP BY Year(DateConsume), Month(DateConsume), ItemID,BOM_Unit, BOM_Consumption_Open) c1
WHERE (YearConsume= 2016 AND MonthConsume = 06)
GROUP BY c1.YearConsume, c1.MonthConsume, c1.cItemID, c1.BOM_Unit) rt
ON le.rItemID = rt.cITemID
WHERE le.rITEMID IN ('FML-RM006', 'FML-RM008','FML-RM016','FML-RM018')

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;

Aggregate query returning multiple rows when I only want one

this is the original query
SELECT 'MSD-RES-CRUISE' AS QUERYNAME, dbo.BOOKINGS.USERID, SUM(dbo.BOOKINGS.APRICE) AS total, COUNT(dbo.BOOKINGS.USERID) AS TOTAL2
FROM dbo.BOOKINGS INNER JOIN dbo.TOURS ON dbo.BOOKINGS.TOUR = dbo.TOURS.TOUR INNER JOIN
dbo.MAJOR ON dbo.TOURS.MAJOR = dbo.MAJOR.MAJOR
WHERE (dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate))) AND (dbo.MAJOR.SDESCR = 'Cruises') AND
(dbo.BOOKINGS.USERID = #USER) AND (dbo.MAJOR.DIVISION = 'A') and dbo.BOOKINGS.STATUS <> 'XL' GROUP BY dbo.BOOKINGS.USERID
the query i want to join
SELECT calltimeint, avetimeint
FROM dbo.agentdailycalls
where userid = #user and date1 between #startdate and #enddate
where the userids match and the groupname matches query name
this is what i used
SELECT t0.QUERYNAME, t0.USERID, total, TOTAL2, calltimeint, avetimeint
FROM ( SELECT 'MSD-RES-CRUISE' AS QUERYNAME, dbo.BOOKINGS.USERID, SUM(dbo.BOOKINGS.APRICE) AS total, COUNT(dbo.BOOKINGS.USERID) AS TOTAL2
FROM dbo.BOOKINGS INNER JOIN dbo.TOURS ON dbo.BOOKINGS.TOUR = dbo.TOURS.TOUR INNER JOIN
dbo.MAJOR ON dbo.TOURS.MAJOR = dbo.MAJOR.MAJOR
WHERE (dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate))) AND (dbo.MAJOR.SDESCR = 'Cruises') AND
(dbo.BOOKINGS.USERID = #USER) AND (dbo.MAJOR.DIVISION = 'A') and dbo.BOOKINGS.STATUS <> 'XL' GROUP BY dbo.BOOKINGS.USERID
) t0
INNER JOIN ( SELECT sum(calltimeint) as calltimeint, sum(avetimeint) as avetimeint , userid
FROM dbo.agentdailycalls
where userid = #user and date1 between #startdate and #enddate and GroupName = 'MSD-RES-CRUISE'
group by userid
) t1 ON t1.userId = t0.USERID
Just do a JOIN on the two queries:
SELECT QUERYNAME, USERID, total, TOTAL2, calltimeint, avetimeint
FROM ('MSD-RES-CRUISE' ... GROUP BY abcfiles.dbo.BOOKINGS.USERID) t0
INNER JOIN (SELECT userid, groupname, calltimeint, avetimeint ... and #enddate) t1
ON t1.userId = t0.USERID AND t01.groupname = t0.QUERYNAME
OLD ANSWER, based on a previous version of the question
Instead of selecting calltimeint and avetimeint it looks like you want to select the SUM of each of those columns, and remove them from the GROUP BY:
SELECT ... SUM(dbo.agentdailycalls.calltimeint), SUM(dbo.agentdailycalls.avetimeint)
FROM dbo.BOOKINGS INNER JOIN ...
GROUP BY dbo.BOOKINGS.USERID
Adding them to the GROUP BY means you want a row for every different combination of these values. So, GROUP BY userid, calltimeint, avetimeint means "return one row for every different combination of userid, call time, and average time".
What you really meant (presumably) is "return one row for each user", so you should only have userid in the GROUP BY.
Try This:
SELECT 'MSD-RES-CRUISE' AS QUERYNAME
, abcfiles.dbo.BOOKINGS.USERID
, SUM(tt.calltime)
, SUM(tt.aveTimeint)
, SUM(abcfiles.dbo.BOOKINGS.APRICE) AS total
, COUNT(abcfiles.dbo.BOOKINGS.USERID) AS TOTAL2
FROM abcfiles.dbo.BOOKINGS
INNER JOIN abcfiles.dbo.TOURS
ON abcfiles.dbo.BOOKINGS.TOUR = abcfiles.dbo.TOURS.TOUR
INNER JOIN abcfiles.dbo.MAJOR
ON abcfiles.dbo.TOURS.MAJOR = abcfiles.dbo.MAJOR.MAJOR
INNER JOIN (SELECT
calltime
, aveTimeint
FROM
dbo.agentdailycalls adc
) tt
ON tt.userid = abcfiles.dbo.BOOKINDS.USERID
AND tt.date1 BETWEEN #startdate AND #endDate***
WHERE (abcfiles.dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate)))
AND (abcfiles.dbo.MAJOR.SDESCR = 'Cruises')
AND (abcfiles.dbo.BOOKINGS.USERID = #USER)
AND (abcfiles.dbo.MAJOR.DIVISION = 'A')
and abcfiles.dbo.BOOKINGS.STATUS <> 'XL'
GROUP BY abcfiles.dbo.BOOKINGS.USERID