I have tried CTE combining two table in my below query and getting the Invalid Object error but it exists .Can Anyone guide me?
;WITH t1
AS (
SELECT DepId
, COUNT(EmpId) AS TotalHeadCount
FROM Emploee
WHERE (datepart(yyyy, DOJ) BETWEEN 2005 AND 2017)
AND STATUS = 0
GROUP BY DepId
)
, t2
AS (
SELECT DepId
, COUNT(EmpId) AS NewJoinees
FROM Emploee
WHERE (DATEPART(yyyy, DOJ) = 2017)
AND (DATEPART(mm, DOJ) = 01)
AND datepart(mm, DOJ) >= 12
AND STATUS = 0
GROUP BY DepId
)
, t3
AS (
SELECT Tobehired AS TOBEHIRED
, OpenPosition AS OPENPOSITION
, STATUS
FROM Employee1
)
SELECT t1.DepId
, CASE
WHEN TotalHeadCount IS NULL
THEN '0'
ELSE TotalHeadCount
END AS TotalHeadCount
, CASE
WHEN NewJoinees IS NULL
THEN '0'
ELSE NewJoinees
END AS NewJoinees
, Tobehired
, OpenPosition
, STATUS
FROM t1
FULL JOIN t2
ON t1.DepId = t2.DepId
FULL JOIN t3
ON t1.DepId = t3.DepId
There's a time and a place for use of Common table expressions. I don't think this was one of them... Complex joins with nested subqueries, recursion, refactoring for maintainability. A two table join doesn't seem to fit the bill in my opinion.
SELECT E.DEPID
, sum(case when datepart(yyyy,E.doj) between 2005 and 2017 and status =0 then 1 else 0 end as TotalHeadCount
, sum(case when E.doj >= cast('2017-01-12' as datetime) then 1 else 0 end as NewJoinees
, E1.Tobehired
, E1.OpenPosition
, E1.STATUS
FROM Employee E
LEFT JOIN Emplyee1 E1
on E.DepID = E1.DepID
GROUP BY E.DEPID,
, E1.Tobehired
, E1.OpenPosition
, E1.STATUS
Related
I have tried to query a piece of code in Oracle, but I continue to receive the error ORA 00933. Can anyone point me to the solution?
This is the piece of code:
SELECT
EXTRACT(MONTH FROM i.invoicedate) AS Month
, CAST(i.invoicedate AS DATE) AS Invoicedate
, I.fiscalinvoiceid
, I.invoiceid
, NULL as Quantity
, I.shipmentcost AS Invoiceprice
, CASE WHEn I.creditinvoiceid IS NOT NULL THEN -1 ELSE 1 END * ROUND((I.shipmentcost *
CASE WHEN I.vatfree = 'N' THEN (1+ (V.vatpercentage / 100)) ELSE 1 END), 2) as 'Total'
, I.vatfree
, creditinvoiceid
, 'Shipment' AS costtype
, I.customerid
, I.subsidiaryid
, EXTRACT(YEAR FROM I.paymentduedate) AS dueyear
, EXTRACT(MONTH FROM I.paymentduedate) AS duemonth
, I.paymentmethodid
FROM VAN_Invoice I
INNER JOIN VAN_VAT V ON I.shipmentcostvatid = V.vatid
I want to get a total sum of the results of my "total tested" "failed" and "passed" colums. I would usually handle these aggregates in SSRS, but I don't have that option at this time.
My current query:
select s.school_code, s.name, count(cd.Test_ID) as [Tested],
sum(case when cd.result = 'fail' then 1 Else 0 End) as 'Failed'
,sum(case when cd.result = 'pass' then 1 Else 0 End) as 'Passed'
FROM
[psi_db_8amSnapshot].[dbo].[Candidate_Data] cd
join [psi_db_8amSnapshot].[dbo].account_school s on s.school_id = cd.school_id
where s.School_code in
(
'1001',
'1002',
'1003' ,
'1004' ,
'1005' ,
'1006' ,
'1007' ,
'1008' ,
'1016' ,
'1009' ,
'1010' ,
'1012' ,
'1013' ,
'1014' ,
'1015'
)
and cd.[date] between '01-01-2016' and '05-01-2017' and cd.TestName = 'MN Dental Assistant State Licensure Examination'
group by s.school_code, s.name, test_id
I am looking to get a total off all the values in my three aggregate columns. So a sum of Tested, which should = 640, sum of passed = 327, sum of failed = 313.
I think you are looking for group by grouping sets as below:
Just replace your group by as below:
group by grouping sets ((s.school_code), (s.name), (test_id))
I would probably use with statements:
with NumberOfFailedResults as
(
Select count(cd.result) as NumberOfFailedResults from [psi_db_8amSnapshot].[dbo].[Candidate_Data] as cd where cd.Result = 'Failed'
),
NumberOfPassedResults as
(
Select count(cd.result) as NumberOfPassedResults from [psi_db_8amSnapshot].[dbo].[Candidate_Data] as cd where cd.Result = 'Passed'
)
Select NumberOfFailedResults, NumberOfPassedResults, ...
This should work for you.
select Q.school_code, Q.name, SUM(Q.Tested), SUM(Q.Failed), SUM(Q.Passed) from (
select s.school_code, s.name, count(cd.Test_ID) as [Tested],
sum(case when cd.result = 'fail' then 1 Else 0 End) as 'Failed'
,sum(case when cd.result = 'pass' then 1 Else 0 End) as 'Passed'
FROM
[psi_db_8amSnapshot].[dbo].[Candidate_Data] cd
join [psi_db_8amSnapshot].[dbo].account_school s on s.school_id = cd.school_id
where s.School_code in
(
'1001',
'1002',
'1003' ,
'1004' ,
'1005' ,
'1006' ,
'1007' ,
'1008' ,
'1016' ,
'1009' ,
'1010' ,
'1012' ,
'1013' ,
'1014' ,
'1015'
)
and cd.[date] between '01-01-2016' and '05-01-2017' and cd.TestName = 'MN Dental Assistant State Licensure Examination'
group by s.school_code, s.name, test_id)Q
GROUP BY Q.School_Code, Q.Name
Below is my query which returns no row and this is correct as per database records.
SELECT CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
YEAR(ReceivedDate) AS CurrentYear ,
CONVERT(VARCHAR, COUNT(CASE WHEN MONTH(ReceivedDate) = 1 THEN 1
ELSE 0
END)) AS Jan
FROM RootTable
WHERE Customerid = 12742
AND YEAR(ReceivedDate) = 2014
GROUP BY CustomerID ,
RForLocation ,
YEAR(ReceivedDate)
But my requirement is that I should get a blank row with customerId, CustType,CurrentYear and Jan Count as Zero (0)
Below is my requirement
CustomerId CustType CurrentYear Jan
12742 Forwarder 2014 0
Thanks
Please Help
SELECT CustomerID
,'Forwarder' AS CustType
,RForLocation
,YEAR(ReceivedDate) AS CurrentYear
,ISNULL(
NULLIF(
COUNT(CASE WHEN MONTH(ReceivedDate) = 1 THEN 1 ELSE 0 END)
, 0)
, '')
AS Jan
FROM RootTable
WHERE Customerid = 12742
AND YEAR(ReceivedDate) = 2014
GROUP BY CustomerID ,
RForLocation ,
YEAR(ReceivedDate)
Whatever I could understand, please find the script and the updated query, with which, I tried it.
Created the table:
Create table RootTable
(CustomerID int,
RForLocation varchar(20),
ReceivedDate datetime)
Inserted the data:
insert into RootTable
Values(1, 'A', '1-Jan-2013'),
(2, 'A', '1-Feb-2013'),
(3, 'B', '1-Jan-2013'),
(4, 'B', '1-Mar-2013')
Query to fetch the records :
SELECT CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
'2014' AS CurrentYear ,
CONVERT(VARCHAR, COUNT(CASE WHEN MONTH(ReceivedDate) = 1 AND YEAR(ReceivedDate) = 2014 THEN 1
ELSE null
END)) AS Jan
FROM RootTable
WHERE Customerid = 1
GROUP BY CustomerID ,
RForLocation;
Since I want record for customer even if he does not have any record for specific year, I don't need to give condition of date in where clause, instead I can do the counting based on year, which will give me required output.
Hope it helps.
Change your CASE statement
CONVERT(VARCHAR, CASE WHEN count(MONTH(ReceivedDate) = 1)
THEN count(MONTH(ReceivedDate) = 1)
ELSE 0
end
SELECT
RootTable.CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
YEAR(ReceivedDate) AS CurrentYear,
SUB1.MON_COL,
CASE WHEN sub1.CNT IS NULL THEN 0 ELSE sub1.CNT END AS CNT
FROM RootTable
LEFT JOIN
(
SELECT COUNT(1) CNT, CustomerId,MONTH(ReceivedDate) AS MON_COL,YEAR(ReceivedDate) AS YEAR_COL
FROM RootTable
GROUP BY CustomerId,MONTH(ReceivedDate),YEAR(ReceivedDate)
) sub1 ON sub1.CustomerID = RootTable.CustomerId AND MONTH(ReceivedDate) = sub1.MON_COL AND YEAR(ReceivedDate) = sub1.YEAR_COL
WHERE RootTable.CustomerId=2
A workmate has given me this stored procedure and asked for help to create an sql INSERT statement based on its results, but am a little confused to some of the methods. For example, I've never seen a CASE statement in sql. I looked it up but the useage is different from what I was given.
Here is the stored procedure
if #ScheduleType Is Null
SELECT Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM Item_Schedule
INNER JOIN Lu_Schedule_Types
ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId
RIGHT OUTER JOIN LmpProjectInfo
ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1)
AND (Item_Schedule.ItemWbsElement = #WbsElement)
AND (Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType
, Lu_Schedule_Types.ScheduleTypeId
, LmpProjectInfo.PlannedQty
, LmpProjectInfo.AuthorizedQty
, LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
I am supposed to be helping him out but I'm by far a database wizard, and am a little out of my depth here. I'd really appreciate the help/advice/direction.
Thanks much!
This is quick sample that might work for you. This assumes that the table you want to insert data into takes all of the values return from the SELECT statement and that they are of the same type.
As a side note, the reason you might have got a bit confused about the CASE statements is possibly due to the fact there are two main ways to use them in SQL. CASE WHEN... like you have here and CASE #value# WHEN #result# THEN.... A little more searching on the web will lead you to some nice examples. For example this one.
INSERT INTO TABLE_NAME
(
ScheduleType,
I01,
I02,
PRD,
PlannedQty,
AuthorizedQty,
WbsElementID
)
SELECT
Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month, Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM
Item_Schedule INNER JOIN
Lu_Schedule_Types ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId RIGHT OUTER JOIN
LmpProjectInfo ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1) AND (Item_Schedule.ItemWbsElement = #WbsElement) AND
(Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType, Lu_Schedule_Types.ScheduleTypeId,
LmpProjectInfo.PlannedQty, LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
Try this one -
INSERT INTO dbo.table1 -- insert in table
(
ScheduleType
, I01
, I02
, PRD
, PlannedQty
, AuthorizedQty
, WbsElementID
)
SELECT
t.ScheduleType
, I01 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 1 THEN ItemQty END)
, I02 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 2 THEN ItemQty END)
, PRD = SUM(CASE WHEN InductionProduction = 2 THEN ItemQty END)
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
--INTO #temp_table -- or insert in temp table
FROM dbo.Item_Schedule s
JOIN dbo.Lu_Schedule_Types t ON s.ItemScheduleType = t.ScheduleTypeId
RIGHT JOIN dbo.LmpProjectInfo i ON s.ItemWbsElement = i.WbsElementID
WHERE s.IsActive = 1
AND s.ItemWbsElement = #WbsElement
AND s.ItemScheduleDate < DATEADD(d, 1, #EndDate))
AND s.ItemScheduleDate >= #StartDate
GROUP BY
t.ScheduleType
, t.ScheduleTypeId
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
ORDER BY t.ScheduleTypeId
I have a query that I am using and I need to get a the value of the previous 12 months, 3 months and last month, yet do not know how to do it.
The current query I have is the following:
select top 100
A.invoice_nbr
, A.invoice_date
, A.ship_from_dc_nbr
, A.ship_to_store_nbr
, A.trailer_id
, B.item_nbr
, C.old_nbr
, C.whpk_qty
, C.vnpk_qty
, C.item_type_code
, D.po_type
, SUM(B.each_ship_qty) as each_ship_qty
, SUM(B.variable_wt_qty) as variable_wt_qty
, SUM(B.ext_cost_amt) as ext_cost_amt
from DB.DC_INVOICE A
inner join DB.DC_INVOICE_LINE B ON A.invoice_nbr = B.invoice_nbr and A.invoice_date = B.invoice_date and A.ship_to_store_nbr = B.ship_to_store_nbr
inner join DB.item C on B.item_nbr = C.item_nbr
left join DB.purchase_order D on B.po_nbr = D.po_nbr
--where A.invoice_date = '2019-09-05' and A.ship_from_dc_nbr = 6011
group by
A.invoice_nbr
, A.invoice_date
, A.ship_from_dc_nbr
, A.ship_to_store_nbr
, A.trailer_id
, B.item_nbr
, C.old_nbr
, C.whpk_qty
, C.vnpk_qty
, C.item_type_code
, D.po_type
I tried adding as another column the following for the "12 months" one:
(SELECT SUM(vnpk_qty)
FROM DB.item C
inner join DB.DC_INVOICE_LINE B ON B.item_nbr = C.item_nbr
inner join DB.DC_INVOICE A ON A.invoice_nbr = B.invoice_nbr and A.ship_to_store_nbr = B.ship_to_store_nbr and BETWEEN DATEADD(dd, A.invoice_date,-365) AND DATEADD(dd, A.invoice_date,-1)
)
However that gave me the error:
[Teradata][ODBC Teradata Driver][Teradata Database] Syntax error: expected something between the 'and' keyword and the 'BETWEEN' keyword.
Any advice on how to get the data I am looking for would be greatly appreciated.
You can use conditional aggregation logic and the ADD_MONTHS function. Here's the general idea:
SELECT
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -12) THEN vnpk_qty END
) AS sum_12month,
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -3) THEN vnpk_qty END
) AS sum_3month,
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -1) THEN vnpk_qty END
) AS sum_1month
FROM DB.DC_INVOICE A
So with your query, it would look like:
select top 100
A.invoice_nbr
, A.invoice_date
, A.ship_from_dc_nbr
, A.ship_to_store_nbr
, A.trailer_id
, B.item_nbr
, C.old_nbr
, C.whpk_qty
, C.vnpk_qty
, C.item_type_code
, D.po_type
, SUM(B.each_ship_qty) as each_ship_qty
, SUM(B.variable_wt_qty) as variable_wt_qty
, SUM(B.ext_cost_amt) as ext_cost_amt
-- New fields
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -12) THEN C.vnpk_qty END
) AS sum_12month,
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -3) THEN C.vnpk_qty END
) AS sum_3month,
SUM(
CASE WHEN A.invoice_date > ADD_MONTHS(CURRENT_DATE, -1) THEN C.vnpk_qty END
) AS sum_1month
-- End new fields
from DB.DC_INVOICE A
inner join DB.DC_INVOICE_LINE B ON A.invoice_nbr = B.invoice_nbr and A.invoice_date = B.invoice_date and A.ship_to_store_nbr = B.ship_to_store_nbr
inner join DB.item C on B.item_nbr = C.item_nbr
left join DB.purchase_order D on B.po_nbr = D.po_nbr
--where A.invoice_date = '2019-09-05' and A.ship_from_dc_nbr = 6011
group by
A.invoice_nbr
, A.invoice_date
, A.ship_from_dc_nbr
, A.ship_to_store_nbr
, A.trailer_id
, B.item_nbr
, C.old_nbr
, C.whpk_qty
, C.vnpk_qty
, C.item_type_code
, D.po_type
You can adapt similar logic to your other SUM()s as needed. It's still a normal SUM except you're choosing when to include a row's value in your calculation based on the invoice_date.