Query executes successfully but returns no results - sql

The following query is used for a report, the report is still showing live data when accesssed, yet when running the query in Management Studio I am not getting any results despite the message 'query successfully completed'
I have had to declare the #Date parameter which I think I have done correctly at the top of the query.
DECLARE #Date datetime;
BEGIN
SET #Date = 27/07/2017;
END
SELECT CAST(CASE WHEN (SOTD_STWH_CODE = 'HPP SHEF') THEN DATE - (CASE
DATEPART(dw, DATE) WHEN 2 THEN 3 ELSE 1 END) ELSE DATE END AS date) AS
ShipDate,
DeFactoUser.F_SO_Transaction.SOTR_CUST_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO,
DeFactoUser.F_SO_Transaction.SOTR_DLSC_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_STWH_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_STRC_CODE,
DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_ORDERED,
DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_OUTSTANDING,
DeFactoUser.F_SO_Transaction_Details.SOTD_QTY_UNITS_PICKED,
DeFactoUser.F_BM_Transactions_Details.BMTD_BMTR_SYS_NO,
DeFactoUser.F_BM_Transactions_Details.BMTD_QTY_OUTSTANDING,
ISNULL(CAST(BaseOn.baseon AS varchar), '') AS BaseOn,
CASE BaseOn.baseonstat WHEN '99' THEN 'Complete' WHEN
'98' THEN 'Outstanding' WHEN '1' THEN 'open' ELSE '' END AS BaseOnStatus,
DeFactoUser.F_SL_Customers.CUST_NAME
FROM DeFactoUser.F_SL_Customers INNER JOIN
DeFactoUser.F_SO_Transaction_Details WITH (NOLOCK) INNER
JOIN
DeFactoUser.F_ST_Products WITH (NOLOCK) ON
DeFactoUser.F_SO_Transaction_Details.SOTD_STRC_CODE =
DeFactoUser.F_ST_Products.STRC_CODE INNER JOIN
DeFactoUser.F_SO_Transaction WITH (NOLOCK) ON
DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO =
DeFactoUser.F_SO_Transaction.SOTR_SYS_NO INNER JOIN
tbl_DFBI_Date ON
DeFactoUser.F_SO_Transaction.SOTR_PROMISED_DATE = tbl_DFBI_Date.Date ON
DeFactoUser.F_SL_Customers.CUST_CODE =
DeFactoUser.F_SO_Transaction_Details.SOTD_CUST_CODE LEFT OUTER JOIN
DeFactoUser.F_BM_Transactions INNER JOIN
DeFactoUser.F_BM_Transactions_Details ON
DeFactoUser.F_BM_Transactions.BMTR_SYS_NO =
DeFactoUser.F_BM_Transactions_Details.BMTD_BMTR_SYS_NO ON
DeFactoUser.F_SO_Transaction_Details.SOTD_SYS_NO =
DeFactoUser.F_BM_Transactions_Details.BMTD_ORDER_LINK_NUMBER LEFT OUTER JOIN
(SELECT RIGHT(SOTR_BASED_ON_REF, 7) AS link,
SOTR_STATUS AS baseonstat, SOTR_SYS_NO AS baseon
FROM DeFactoUser.F_SO_Transaction AS
F_SO_Transaction_1
WHERE (SOTR_CUST_CODE = 'h075') AND
(SOTR_BASED_ON_REF > '0')) AS BaseOn ON
CAST(DeFactoUser.F_SO_Transaction_Details.SOTD_HEAD_NO AS varchar) =
BaseOn.link
WHERE (DeFactoUser.F_ST_Products.STRC_NI_CODE = 'panelcut') AND
(DeFactoUser.F_ST_Products.STRC_ANAL1 = '1033') AND
(DeFactoUser.F_SO_Transaction_Details.SOTD_SOTR_TYPE = 10) AND
(DeFactoUser.F_SO_Transaction.SOTR_CUST_CODE <> 'h075')
AND (DeFactoUser.F_SO_Transaction.SOTR_STATUS < '99') AND (CASE WHEN
(SOTD_STWH_CODE = 'HPP SHEF')
THEN DATE - (CASE DATEPART(dw, DATE) WHEN 2 THEN 3 ELSE 1
END) ELSE DATE END <= #Date)
Any suggestions as to how i can view the results?

You need the following to initialize the date:
SET #Date = '20170727'; -- Format as YYYYMMDD which is locale neutral
What you currently have is, 27 divided by 7 divided by 2017. These are integers, so the result is 0. This number is then converted to datetime, which will not result in the date you intended to have.
You best stick to the ISO 8601 formatting of dates, or date/time values. You can read more about that in the DATETIME documentation.

Related

Adding between dates - sql query

Currently I have a query that will get me the data from the pervious month .
I need to change thisso I can choose a selected date range that could allow me to input 2 dates and pull back all results between them.
See my query below:
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and month(I.Date_Key) = (select case when Month (GETDATE())-1 = 0 then 12 else Month (GETDATE())-1 end)
and year(I.Date_Key) = (select case when Month (GETDATE()) -1 = 0 then year (GETDATE()) -1 ELSE YEAR (GETDATE()) end)
I need to be able to say where dates between dd/mm/yy and dd/mm/yy
You could declare the dates a variables:
Declare #Startdate as datetime
Declare #Enddate as datetime
set #Startdate = '01-AUG-20'
set #Enddate = '22-OCT-20'
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and I.Date_Key > #Startdate
and I.Date_Key < #Enddate
A simple method is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
datediff(month, i.Date_key, getdate()) = 1
That version, however, cannot use an index on i.Date_Key if that is appropriate. A more index friendly version is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
i.Date_key < datefromparts(year(getdate()), month(getdate()), 1) and
i.Date_key >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

How do I include records in a Summary query to include those that don't have data?

I have a query on a transaction table that returns the Summarized total on a column for each ID based on a data range. The query works great except it doesn't include those IDs that don't have data in the transaction table. How can I include those IDs in my result filled with a zero total. Here's a simplified version of my query.
SELECT tblID.IDName
,SUM(CASE
WHEN tblTransactions.idxTransType = 30
THEN CAST(tblTransactions.TimeAmount AS FLOAT) / 60.0
ELSE 0
END) AS 'Vacation'
FROM tblTransactions
INNER JOIN tblTransTypes ON tblTransactions.idxTransType = tblTransTypes.IdxTransType
INNER JOIN tblID ON tblTransactions.idxID = tblID.IdxID
WHERE (tblTransactions.Deleted = 0)
AND (tblTransactions.NotCurrent = 0)
AND (tblTransactions.TransDate >= CONVERT(DATETIME, 'March 1, 2018', 102))
AND (tblTransactions.TransDate <= CONVERT(DATETIME, 'April 11, 2018', 102))
GROUP BY tblID.IDName
Actually it's slightly more complicated than that:
SELECT
i.IDName,
SUM(CASE WHEN t.idxTransType = 30 THEN CAST(t.TimeAmount AS FLOAT) / 60.0 ELSE 0 END) AS 'Vacation'
FROM
tblID i
LEFT JOIN tblTransactions t ON t.idxID = i.IdxID AND t.Deleted = 0 AND t.NotCurrent = 0 AND t.TransDate BETWEEN '20180301' AND '20180411'
LEFT JOIN tblTransTypes tt ON tt.IdxTransType = t.idxTransType
GROUP BY
i.IDName;
You want left joins:
SELECT i.IDName,
SUM(CASE WHEN t.idxTransType = 30 THEN CAST(t.TimeAmount AS Float) / 60.0 ELSE 0 END) AS Vacation
FROM tblID i LEFT JOIN
tblTransactions t
ON t.idxID = i.IdxID AND
t.Deleted = 0 AND
t.NotCurrent = 0 AND
t.TransDate >= '2018-03-01' AND
t.TransDate <= '2018-04-11'
tblTransTypes tt
ON t.idxTransType = tt.IdxTransType
GROUP BY i.IDName;
Notes:
Table aliases make the query much easier to write and to read.
Use ISO/ANSI standard date formats.
The filter conditions on all but the first table belong in the ON clauses.

How to return count in 2 columns?

I have this query. It should return Count for both AWARDED (1) and NOT AWARDED(0) works from works table.
Select Count(w.WorkID)as Total, w.IsAwarded, org.OrganizationName
From Works w
Inner Join MC_MemberShip.Membership.Organization org
ON org.OrganizationID= w.Organization_ID
where Convert(varchar(11), w.OpeningDate) >= Convert(varchar(11), #FromDate)
and Convert(varchar(11), w.OpeningDate) < DATEADD(day, 1, Convert(varchar(11), #ToDate))
and w.IsActive=1 and
ISNULL(w.IsAwarded,0)= 0 and w.Organization_ID= case when #OrgID= -1 then w.Organization_ID else #OrgID end
group by org.OrganizationName, w.IsAwarded
Now this query returns Total count for NOT AWARDED i.e. 0 only but i want to return count for AWARDED too in same query.
Organization TotalAwardedWorks TotalNotAwardedWorks
Town 1 1 2
Town 2 44 33
Your query should look something like this:
select org.OrganizationName,
Count(*) as Total,
sum(case when w.IsAwarded = 0 or w.IsAwarded is null then 1 else 0 end) as TotalNotAward,
sum(case when w.IsAwarded = 1 then 0 else 1 end) as TotalAward
from Works w Inner Join
MC_MemberShip.Membership.Organization org
on org.OrganizationID = w.Organization_ID
where w.OpeningDate >= #FromDate and
w.OpeningDate < dateadd(day, 1, #ToDate) and
w.IsActive = 1 and
(w.Organization_ID = #OrgId or #OrgID= -1)
group by org.OrganizationName;
Notes:
Do not convert dates to strings to perform comparisons. That is just perverse.
Generally, the use of case in the where clause is discouraged. The logic is more clearly represented using or.
You can get what you want by using case to put conditions in the aggregation functions.

SQL Ignores Nested Case

I'm creating a Date_Dimension and have the Problem that i have to define "lastworkingdayofmonth" with Setting a flag on it.
I can handle all days but when the calculated they is a Holiday i cant get the day before to set the flag.
Please help me :)
UPDATE DATE_DIMENSION_001
SET ISLASTWORKINGDAYMONTH =
CASE WHEN ( CONVERT(VARCHAR(8), lastdayofmonth, 112) = Datekey ) AND IsWeekday = 1 AND IsHolidayAut = 0 THEN 1
WHEN ( CONVERT(VARCHAR(8), dbo.fn_LastWorkday(FullDate), 112) ) = Datekey AND IsHolidayAut = 0 THEN 1
WHEN ( CONVERT(VARCHAR(8), dbo.fn_LastWorkday(FullDate), 112) ) = Datekey AND IsHolidayAut = 1 THEN
CASE WHEN ( DATEADD(DD, -1, dbo.fn_LastWorkday(FullDate)) ) = CONVERT(DATE, Datekey) THEN 1
END
END
I think that something like this may work for you:
UPDATE dd
SET ISLASTWORKINGDAYMONTH = 1
FROM
DATE_DIMENSION_001 dd
left join
DATE_DIMENSION_001 dd_anti
on
DATEPART(year,dd.FullDate) = DATEPART(year,dd_anti.FullDate) and
DATEPART(month,dd.FullDate) = DATEPART(month,dd_anti.FullDate) and
dd_anti.FullDate > dd.FullDate and
dd_anti.IsWeekday = 1 and
dd_anti.IsHolidayAut = 0
WHERE
dd.IsWeekday = 1 and
dd.IsHolidayAut = 0 and
dd_anti.FullDate is null
That is, we locate rows which are weekdays, not holidays, and for which (via dd_anti, the LEFT JOIN and the null check in the WHERE clause) we cannot locate another row for the same month, but a later date, and is also a weekday and not a holiday.

multi-select sql query with date range

I have this query where I get totals of different stats from an employee roster table.
SELECT A.rempid AS EmpId,
E.flname,
A.rdo_total,
B.grave_total,
C.sundays,
D.holidays
FROM (SELECT rempid,
Count(rshiftid)AS RDO_Total
FROM rtmp1
WHERE rshiftid = 2
GROUP BY rempid
HAVING Count(rshiftid) > 0) A,
(SELECT rempid,
Count(rshiftid)AS Grave_Total
FROM rtmp1
WHERE rshiftid = 6
GROUP BY rempid
HAVING Count(rshiftid) > 0)B,
(SELECT rempid,
Count(rshiftid) AS Sundays
FROM rtmp1
WHERE Datepart(dw, rdate) = 1
AND rshiftid > 2
GROUP BY rempid
HAVING Count(rshiftid) > 0)C,
(SELECT rempid,
Count(rshiftid) AS Holidays
FROM rtmp1
WHERE rdate IN (SELECT pubhdt
FROM pubhol)
AND rshiftid > 2
GROUP BY rempid
HAVING Count(rshiftid) > 0)D,
(SELECT empid,
[fname] + ' ' + [sname] AS flName
FROM remp1)E
WHERE A.rempid = B.rempid
AND A.rempid = E.empid
AND A.rempid = C.rempid
AND A.rempid = D.rempid
ORDER BY A.rempid
I would like to add a date range into it, so that I can query the database within 2 dates. The rTmp1 table has a column called rDate. I was wondering what the best way to do this. I could add it to a stored procedure and add variable to each select query. Or is there a better way to run the query within a date range.
i think just add an additional where clause item similar to:
AND ( rDate > somedate AND rDate < someotherdate )
Adding the date range to each query is the most direct solution.
Making it a stored procedure is something that can always be done with a query, but has nothing to do with this specific case.
If the number of records resulting from narrowing down your table to the specified date range is substantially less than the entire table, it might be an option to insert these records into a temporary table or a table variable and run your existing query on that table/resultset.
Though I do not have any data to test, you might consider the following query as it is more easy to read and might perform better. But you have to check the results for yourself and maybe do some adjustments.
DECLARE #startDate date = '12/01/2012'
DECLARE #endDate date = DATEADD(MONTH, 1, #startDate)
SELECT
[e].[empid],
[e].[fname] + ' ' + [e].[sname] AS [flName],
SUM(CASE WHEN [t].[rshiftid] = 2 THEN 1 ELSE 0 END) AS [RDO_Total],
SUM(CASE WHEN [t].[rshiftid] = 6 THEN 1 ELSE 0 END) AS [Grave_Total],
SUM(CASE WHEN [t].[rshiftid] > 2 AND DATEPART(dw, [t].[rdate]) = 1 THEN 1 ELSE 0 END) AS [Sundays],
SUM(CASE WHEN [t].[rshiftid] > 2 AND [h].[pubhdt] IS NOT NULL THEN 1 ELSE 0 END) AS [Holidays]
FROM [remp1] [e]
INNER JOIN [rtmp1] [t] ON [e].[empid] = [t].[rempid]
LEFT JOIN [pubhol] [h] ON [t].[rdate] = [h].[pubhdt]
WHERE [t].[rdate] BETWEEN #startDate AND #endDate
GROUP BY
[e].[empid],
[e].[fname],
[e].[sname]
ORDER BY [empid] ASC