I am writing a query to return some info, but the stored procedure wont return the results in the page because the values dont match the table definition. i understand this error. but i'm using the case statement to filtering based off a field (whether the t.TimeCallWasReceived is received or not). when i do this, it allows for the sp to run while either the user checking the db for changes or using signalR to detect db changes. I dont want the CASE statement to be a part of my results. i know i can alter the page or the temp table, but i want to know if there is anything i can do in t-sql to return the results without the case statement in said results. the query is below.
SELECT DISTINCT
c.Num,
'Notified for pickup ' + (CONVERT(varchar(30), c.ServiceCalled, 100)) + '. Number ' + c.Num AS Issue,
RTRIM(c.NameFirst) + ' ' + RTRIM(c.NameLast) AS CusName,
(CASE
WHEN t.TimeCallWasReceived IS NULL THEN CONVERT(varchar(20), t.TimeCallWasReceived, 113)
ELSE 'NO'
END) AS CallReceivedAt
FROM tblCustomer c
LEFT JOIN tblTransportation t ON t.Num = c.Num
WHERE t.TimeCallWasReceived IS NULL
AND c.Type = 'Type1'
AND c.ServiceCalled IS NOT NULL
AND c.TransportNum IS NULL
AND LEFT(c.Num, 2) <> 'CR'
AND LEFT(c.Num, 2) <> 'TR'
AND (c.Status <> 'Void'
OR c.Status <> 'Closed')
AND ((DATEDIFF(MINUTE, c.ServiceCalled, GETDATE())) > 180)
AND c.Type <> 'VOID'
AND c.Type <> 'NON'
AND c.Type <> 'Walk-In'
AND c.Type <> 'CFR'
AND c.CaseType <> 'PAP'
AND c.ServiceCalled >= DATEADD(DAY, -2, GETDATE())
ORDER BY c.Num DESC;
--1. Since the WHERE clause has `t.TimeCallWasReceived IS NULL`, you will see only ---'NO' in the CallReceivedAt result column.
--2. Since the WHERE clause has `c.Type = 'Type1'`, it makes unnecessary to look for
c.Type <> 'VOID'
c.Type <> 'NON'
c.Type <> 'Walk-In'
c.Type <> 'CFR'
--because they are exclusive for the rest of the values different than 'Type1'.
--3. I don't see a way to get rid of the CASE
-- Perhaps you like this way better:
CASE ISNULL(t.TimeCallWasReceived, '')
WHEN '' THEN CONVERT(varchar(20), t.TimeCallWasReceived, 113)
ELSE 'NO'
END
Related
I want to write a CASE statement to find the data between two dates based on #sFRomDate empty or not. Given below query not working as per my requirement. Please help me to find a proper solution
SELECT
*
FROM
tbl_emp_data
WHERE
CASE
WHEN #sFRomDate!=''
THEN SubmissionDate BETWEEN #sFRomDate AND DATEADD(DAY,1,#sToDate)
ELSE
SubmissionDate = NULL
END
This might be the logic you were trying to implement. In the event that #sFRomDate be NULL or empty and SubmissionDate also be NULL or empty the record will be returned. Otherwise, the SubmissionDate will be checked to make sure it is within the range you defined.
SELECT *
FROM tbl_emp_data
WHERE (COALESCE(#sFRomDate, '') = '' AND
COALESCE(SubmissionDate, '') = '') OR
(COALESCE(#sFRomDate, '') <> '' AND
COALESCE(SubmissionDate, '') <> '' AND
SubmissionDate BETWEEN #sFRomDate AND DATEADD(DAY, 1, #sToDate))
If I understand what you want, I think it becomes simpler to follow the logic if you write:
IF #sFromDate = ''
BEGIN
SELECT * FROM tbl_emp_data where SubmissionDate=null
END
ELSE
BEGIN
SELECT * FROM tbl_emp_data where SubmissionDate between #sFRomDate and DATEADD(DAY,1,#sToDate)
END
But as #Tim Biegeleisen says, be careful with nulls, not just for #sFromDate but also #sToDate
Using Pentaho Report Designer I want to take data from columns in a database and have this data displayed in a line.
See my example below. Is there a way I can accomplish this?
My database table looks like this:
GENUS SPECIFIC_EPITHET SPECIES_AUTHOR
Asplenium scolopendrium L.
Asplenium bradleyi D.C. Eaton
Asplenium platyneuron (L.) Britton, Sterns & Poggenb.
Asplenium viride Huds.
I would like the report to look like this:
Asplenium scolopendrium L., Asplenium bradleyi D.C. Eaton, Asplenium platyneuron (L.) Britton, Sterns & Poggenb., Asplenium viride Huds.
I am only able to get the report to show the data in a column like list as shown below.
Asplenium scolopendrium L.
Asplenium bradleyi D.C. Eaton
Asplenium platyneuron (L.) Britton, Sterns & Poggenb.
Asplenium viride Huds.
It would also be helpful if someone would tell me if this is not possible in PRD.
I figured this out thanks to being shown how by Deanicus on the Pentaho Reporting Forum (see here).
The main trick was to query my database before I got my data into the report via PRD. Since I am working with a POSTGRESQL database the code I used to query the database looked something like this.
SELECT
string_agg(CONCAT(CONCAT(CONCAT(
c."genus", ' '),
c."specific_epithet",' '),
c."species_author"),', ') as scinamewauthor
FROM
"public"."main_checklist" as c
My final query was actually a lot more complicated since I was adding all sorts of spaces and html formatting marks. The entire piece of code actually looks like this.
SELECT
string_agg (CONCAT(
(SELECT CASE WHEN s."genus_synonym" IS NULL THEN '' ELSE '<i>'||s."genus_synonym"||'</i>' END),
(SELECT CASE WHEN s."specific_epithet_synonym" IS NULL THEN '' ELSE ' <i>'||s."specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."species_author_synonym" IS NULL THEN '' ELSE ' '||s."species_author_synonym" END),
(SELECT CASE WHEN s."subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. '||'<i>'||s."subspecific_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."subspecies author_synonym" IS NULL THEN '' ELSE ' '|| s."subspecies author_synonym" END),
(SELECT CASE WHEN s."varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."varietal_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."variety_author_synonym" IS NULL THEN '' ELSE ' '|| s."variety_author_synonym" END),
(SELECT CASE WHEN s."misapplied" = 'misapplied hybrid formula 1' THEN ' misapplied' ELSE '' END),
(SELECT CASE WHEN s."hybrid_formula_genus_synonym" is null THEN '' ELSE ' × <i>'||substring("hybrid_formula_genus_synonym" from 1 for 1)||'.</i>'END),
(SELECT CASE WHEN s."hybrid_formula_specific_epithet_synonym" is null THEN '' ELSE ' <i>'|| s."hybrid_formula_specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_formula_species_author_synonym" is null THEN '' ELSE ' '||s."hybrid_formula_species_author_synonym" END),
(SELECT CASE WHEN s."hybrid_formula_subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. <i>'||s."hybrid_formula_subspecific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_formula_subspecies_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_formula_subspecies_author_synonym" END),
(SELECT CASE WHEN s."hybrid_formula_varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."hybrid_formula_varietal_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_formula_variety_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_formula_variety_author_synonym"END),
(SELECT CASE WHEN s."misapplied" = 'misapplied hybrid formula 2' THEN ' misapplied' ELSE '' END),
(SELECT CASE WHEN s."genus_hybrid_synonym" IS NULL THEN '' ELSE '×'End),
(SELECT CASE WHEN s."hybrid_name_genus_synonym" IS NULL THEN ''
WHEN s."genus_synonym" IS NULL THEN '<i>'||s."hybrid_name_genus_synonym"||'</i>'
Else ' = <i>'||"hybrid_name_genus_synonym" ||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_specific_epithet_synonym" IS NULL THEN ''
when s."genus_hybrid_synonym" is null then ' ×<i>'||s."hybrid_name_specific_epithet_synonym"||'</i>'
ELSE ' <i>'||s."hybrid_name_specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_name_species_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_name_species_author_synonym" END),
(SELECT CASE WHEN s."hybrid_name_subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. <i>'||s."hybrid_name_subspecific_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_subspecies_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_name_subspecies_author_synonym"END),
(SELECT CASE WHEN s."hybrid_name_varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."hybrid_name_varietal_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_variety_author_synonym" IS NULL THEN '' ELSE ' 'END),
s."hybrid_name_variety_author_synonym",
(SELECT CASE WHEN (s."misapplied" IS NULL or s."misapplied" = 'misapplied hybrid formula 1' or s."misapplied" = 'misapplied hybrid formula 2') Then ''
WHEN s."misapplied" = 'misapplied hybrid name' Then ' misapplied'
Else ' '||"misapplied" END)),
', '
Order by s."genus_synonym" ASC,
s."specific_epithet_synonym" ASC,
s."varietal_epithet_synonym" ASC NULLS FIRST,
s."subspecific_epithet_synonym" ASC NULLS FIRST,
s."hybrid_formula_specific_epithet_synonym" ASC,
s."hybrid_formula_subspecific_epithet_synonym" ASC,
s."hybrid_formula_varietal_epithet_synonym" ASC,
s."hybrid_name_specific_epithet_synonym" ASC)as syno
FROM
"public"."synonyms" as s INNER JOIN "public"."main_checklist" ON s."record_id" = "public"."main_checklist"."record_id"
WHERE
s."record_id" = ${import_record_id}
I have this piece of code (please look below). I keep getting error: "Invalid column name 'SuppFinish2'
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2],
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
FROM TABLE
Is it because of [SuppFinish2] being an alias? Thanks!
As you said its due to alias and aliased columns can be referenced only on order by to logical query flow order
with cte
as
(
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2]
FROM TABLE
)
select
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
from cte
You cant use those aliases in the same level as you created them, becuase they are not existing yet.. wrap your query with another select like this:
SELECT * ,
CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST]
FROM (
SELECT
[ID],
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2],
FROM TABLE)
In order to reference aliased columns, you can use a derived table (or CTE, but that is not shown here)
Select *, CASE
WHEN [RegFinish]<[SuppFinish2] THEN '1'
ELSE '0'
END AS [TEST] From
(
SELECT
CASE
WHEN [RegFinish] IS NULL THEN ''
ELSE [RegFinish]
END AS [RegFinish],
CASE
WHEN [SuppFinish] IS NULL THEN ''
ELSE [SuppFinish]
END AS [SuppFinish2]
) T1
FROM TABLE
You cannot, at the same time, set and access an alias in the SELECT clause. I would suggest rewriting your query using CROSS APPLY:
SELECT t1.[RegFinish],
t2.[SuppFinish],
CASE
WHEN t1.[RegFinish] < t2.[SuppFinish] THEN '1'
ELSE '0'
END AS [TEST]
FROM TABLE
CROSS APPLY (SELECT COALESCE([RegFinish], '') AS [RegFinish]) AS t1
CROSS APPLY (SELECT COALESCE([SuppFinish], '') AS [SuppFinish]) AS t2
SELECT ISNULL([RegFinish],'') as [RegFinish]
, ISNULL([SuppFinish],'') as [SuppFinish2], CASE
WHEN
ISNULL([RegFinish],'') < ISNULL([SuppFinish],'') THEN 1
ELSE 0
END AS [TEST]
FROM TABLE
Why not use ISNULL instead of CASE? The problem with your query is that [SuppFinish2] is an alias not an column and can only be used in ORDER BY clause
I am writing a CASE statement in my SQL Server Stored Procedure. There I am repeeating a same long SQL statements every time for 11 CASEs. Should I put the SQL Statement in CASE condition in a another Stored Procedure? What could be the best approach?
CASE (SELECT ..................)
THEN 'SELCET a.field'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
CASE (SELECT ..................)
THEN 'SELCET vaues'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
You might want to do something like
SELECT
CASE (your select statement which retuns one value)
WHEN 'option1' THEN 'value2return1'
WHEN 'option2' THEN 'value2return2'
WHEN 'option3' THEN 'value2return3'
...
ELSE 'defaultValue'
END
Use common table expressions link.
WITH CTE (ColA)
AS
(
Select ColA From Table
)
SELECT ColA
FROM CTE
Use a CTE. In the future it would help if you gave us a slightly better example of your code however.
WITH RepeateSelect AS (SELECT ..................)
.....
.....
CASE (SELECT * FROM RepeateSelect)
THEN 'SELCET a.field'
ELSE
'SELECT vlaues'
END
as 'Coulmn1 '
CASE (SELECT * FROM RepeateSelect)
THEN 'SELCET vaues'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
Try using the repeated query once thusly:
select A.C1, X.C2, X.C3
from TableA as A inner join
( select B.AlmondJoy,
case when B.YN > 7 then 'Yes' else 'No' end as C2,
case when C.UD in ( -1, 1 ) then 'Up' else 'Down' end as C3
from TableB as B inner join
TableC as C on C.Id = B.Id
) as X on X.AlmondJoy = A.Zagnut
I'm having an issue with the below query:
SELECT
Consignments.LegacyID,
Consignments.TripDate,
Consignments.CollectionName,
CASE
WHEN Sage2.InvoiceSummaryType = 'HT' THEN DeliveryTown
ELSE DeliveryName + ', ' + DeliveryTown + ', ' + DeliveryPostCode END AS 'DeliveryName',
Consignments.Pallets,
Consignments.Weight,
Consignments.BaseRate,
Consignments.FuelSurcharge,
Consignments.AdditionalCharges,
Consignments.BaseRate * Consignments.Quantity AS 'InvoiceValue',
Consignments.InvoiceNumber,
Consignments.Customer
FROM
Consignments
INNER JOIN SageAccount
ON Consignments.Customer = SageAccount.LegacyID
AND SageAccount.Customer = 'true'
LEFT OUTER JOIN SageAccount AS Sage2
ON SageAccount.InvoiceAccount = Sage2.LegacyID
WHERE
(Sage2.Customer = 'true')
AND (Consignments.Customer = #Customer)
AND (Consignments.InvoiceNumber IS NOT NULL)
OR (Sage2.Customer = 'true')
AND (Consignments.InvoiceNumber IS NOT NULL)
AND (Sage2.InvoiceAccount = #Customer)
ORDER BY
CASE
WHEN Sage2.InvoiceSummaryType = 'HR' THEN TripDate
WHEN Sage2.InvoiceSummaryType = 'HS' THEN Consignments.LegacyID
END
For some reason, it keeps giving me the following error:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value order by
But only when it tries to Order By TripDate, i.e. when the case 'HR' happens. TripDate is a 'datetime field'.
Any ideas?
Having just read the question again I can't explain the specific symptons you are getting without seeing the execution plan (I would have expected HS to cause the problem). Generally though you should avoid mixing datatypes in CASE expressions as below as it simply doesn't work select case when 1=0 then GETDATE() else 'foo' end will fail as it tries to convert the string to datetime
ORDER BY
CASE
WHEN Sage2.InvoiceSummaryType = 'HR'
THEN TripDate
WHEN Sage2.InvoiceSummaryType = 'HS'
THEN Consignments.LegacyID
END
To get around this you can use cast(TripDate as float) - assuming (perhaps incorrectly) that the ID field is numeric or use this idiom.
ORDER BY
CASE
WHEN Sage2.InvoiceSummaryType = 'HR'
THEN TripDate
ELSE NULL
END,
CASE
WHEN Sage2.InvoiceSummaryType = 'HS'
THEN Consignments.LegacyID
ELSE NULL
END
You would need to check the execution plans for performance comparisons.
Don't you need an "END" after your THEN TripDate ?
All the options in the CASE statement have to be the same datatype. Is LegacyID a char?
You'd have this problem anywhere, not just in an order by. If you do CASE WHEN 'x' THEN (some int) WHEN 'y' THEN (some date) and SQL cannot do an implicit conversion of all values, then you're toast.
If you're doing a cased ordering, then the data types have to be compatible with each other.
try this for the date:
Convert(int, TripDate , 112)
A format of 112 will give you yyyymmdd, which is useful in ordering by date as an integer. Use 1 - [date] for descending.
This is assuming that the LegacyID is an integer. Otherwise, you can try casting the date to a type SQL_VARIANT