CTE with CASE statement - sql-server-2008-r2

I'm trying a query like this;
WITH CTE AS
(
SELECT
ID, NAME, DEPT,
CASE WHEN Fixed = 1 THEN 'Yes' ELSE '' END,
CASE WHEN NotFixed = 1 THEN 'Yes' ELSE '' END,
)
When I try to execute this query, I'm getting error like
No Column was specified for column 4 of CTE
What's wrong with the query?

Read the error message: You forgot to give your calculated columns a name. This goes for both column 4 and column 5. So change your query to something like this:
WITH CTE AS
(
SELECT
ID, NAME, DEPT,
CASE WHEN Fixed = 1 THEN 'Yes' ELSE '' END AS [Expr1],
CASE WHEN NotFixed = 1 THEN 'Yes' ELSE '' END AS [Expr2],
. . .
)
Feel free to change [Expr1] and [Expr2] to something more meaningful...

Related

How to perform Grouping equivalent like Informatica?

I've an Informatica function which I want to convert into query to be getting used in Spring Batch code.
I've a table EMPLOYEE table having 15 fields (all I want in select) and Informatica has function Router which creates group based on STATUS_CD = 'A' and default (means all other records should go here - where status is other than A).
How can we do in Postgres?
I've all the employees and I want to check based using combination of EMPLOYEE_CD, EMPLOYEE_ID is unique and I want to simply return the count of it.
Query1
SELECT EMPLOYEE_CD AS EMPLOYEE_CD,
EMPLOYEE_ID AS EMPLOYEE_ID,
COUNT (*) AS CNT
FROM EMPLOYEE
GROUP BY EMPLOYEE_CD, EMPLOYEE_ID
HAVING COUNT (*) > 1;
Query 2
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, EMPLOYEE_EMAIL, EMPLOYEE_PHONE, EMPLOYEE_ADDRESS, (Create Count Field here)
FROM EMPLOYEE
Query 3 - I need to group (which is my original question) or Create Columns ACTIVE, NON_ACTIVE columns as a part of query results where EMPLOYEE_STAT_CD = 'A', ACTIVE column value should say YES and EMPLOYEE_STAT_CD other than A, NON_ACTIVE should say Yes.
How can merge Query1 and Query 2 and Query 3 into single query ?
if I understood the question, your code is something like:
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, EMPLOYEE_EMAIL, EMPLOYEE_PHONE, EMPLOYEE_ADDRESS,
COUNT(*)OVER(PARTITION BY EMPLOYEE_CD, EMPLOYEE_ID) AS counter_from_sql1,
CASE WHEN EMPLOYEE_STAT_CD = 'A' THEN 'YES' ELSE NULL END AS ACTIVE,
CASE WHEN EMPLOYEE_STAT_CD <> 'A' THEN 'YES' ELSE NULL END AS NON_ACTIVE
FROM EMPLOYEE;
or
SELECT * FROM (
SELECT EMPLOYEE_ID, EMPLOYEE_NAME, EMPLOYEE_EMAIL, EMPLOYEE_PHONE, EMPLOYEE_ADDRESS,
COUNT(*)OVER(PARTITION BY EMPLOYEE_CD, EMPLOYEE_ID) AS counter_from_sql1,
CASE WHEN EMPLOYEE_STAT_CD = 'A' THEN 'YES' ELSE NULL END AS ACTIVE,
CASE WHEN EMPLOYEE_STAT_CD <> 'A' THEN 'YES' ELSE NULL END AS NON_ACTIVE
FROM EMPLOYEE
) z
WHERE counter_from_sql1 > 1;

SQL Select where exclusive Or /Case

I need a query based on an exclusive Or statement for this I try using the case but I won't get a result in case of Null...
...
and b.[U_Periode] = CASE
when (b.U_Periode= #period) then #period
when (b.U_Periode is NULL ) then null
end
...
The Case that won't be catched is... if B.U_Status is null and b.U_Periode is null.
If the var Periode match the Value and the U_Status = 0 or 1
the only way getting this working for me was this:
...
and
ISNULL( b.[U_Status],'0') = CASE
when (b.U_Status= '1') then '1'
when (isnull( b.U_Status,'0')= '0') then '0'
end
and
ISNULL (b.[U_Periode],'01.01.1901') = CASE
when (b.U_Periode= #period) then #period
when (ISNULL (b.U_Periode,'01.01.1901') = '01.01.1901' ) then '01.01.1901'
end
are there any other better solutions for this?
Best regards
Oliver
Okay... here is my Problem
Table1
InsID ContractID
1 1
2 1
Table2
ID insid Period Status Count
1 1 null null 100
2 1 30.09.2015 1 500
3 2 null null 100
4 2 30.09.2015 1 500
Case '31.08.2015'
in total Value should be 200
in case of '30.09.2015'
the Value should be 1.000
XOR /OR will do the same in this case.
Value case '31.08.2015' = 200
value Case ' 30.09.2015 = 2200
So this is somesing like a subquery
left join (
[dbo].[Table2]b
inner join [dbo].[Table 3]K on k.DocEntry = b.DocEntry and CAST( k.U_CSetID as int) >0
)
on b.[U_InsID] in(select... but here I should have an if statement...
If there are results matching the Date join this
If not than join the result NULL is matching to periode...
Okay.. here is the complete query
the Table2 with the Date of 31.08.2015 should have one Record that include
B_STATUS = Null and B.Preiode = null and there is no available record with the U_Periode '31.08.2015' and a Staus ...
with a date of 30.09.2015
there is a Record matching U_Period = '30.09.2015' in this case the Record with U_Period=null should not effect the result...
Declare #period as varchar(20)= '31-08-2015 00:00:00'
declare #Customer as Varchar(15)='12345'
declare #Contract as varchar(30) = '123'
declare #test as varchar(1) = null
select SUM(cast(K.U_Count as decimal))as counter, K.U_CounterTyp
from [dbo].[Table1] a
left join (
[dbo].[Table2]b
inner join [dbo].[Table 3]K on k.DocEntry = b.DocEntry and CAST( k.U_CSetID as int) >0
)
on b.[U_InsID]=a.[insID] and b.[U_ObjectType]in ('5','1') and
ISNULL( b.[U_Status],'0') = CASE
when (b.U_Status= '1') then '1'
when (isnull( b.U_Status,'0')= '0') then '0'
end
and
ISNULL (b.[U_Periode],'01.01.1901') = CASE
when (b.U_Periode= #period) then #period
when (ISNULL (b.U_Periode,'01.01.1901') = '01.01.1901' ) then '01.01.1901'
end
where a.[customer] =#Customer and a.[Status]='A' and a.[U_ContrCount]='1'
and a.[manufSN] in(
select c.[ManufSN] from [dbo].[Table4] c
inner join [dbo].[OCTR]d on d.[ContractID] = c.[ContractID]
where c.[ManufSN]=a.[manufSN]
and d.[CstmrCode] = a.[customer] and d.[ContractID]=#Contract
)
group by K.U_CounterTyp
you must use the "^" operand, this is XOR operand in TSQL
expression ^ expression
the expression must return or 0 or 1...
stupid example:
WHERE (name like "stackoverflow") ^ (age > 10)
font: https://msdn.microsoft.com/en-us/library/ms190277(v=sql.105).aspx
Update for your check
WHERE (CONVERT(VARCHAR(10), a.[U_Periode], 104) = '30.08.2015') != (a.U_Periode IS NULL)
Olay here is my funktion that chek either a Date Result is there or not.
The only thing is, that the performance is not the best if I run hundreths of sentences ... foreach record (up to app. 1000) I need to query each subtable... and there are many many records in...
Anyway this is the function
CREATE FUNCTION fn_GetInsCounters(#InsId as Varchar(30), #Date as datetime)
returns datetime
as
begin
declare #count as int = 0
declare #Retruns as Datetime
set #count =
(
select count( b.Docentry)
from [dbo].[Table2]b
where b.U_Insid =#InsID
and b.U_Status <> '2'
and b.[U_ObjectType]in ('5','1')
and b.U_Periode=#Date
)
if(#count>0)
begin
set #Retruns = #date
end
else
begin
set #Retruns = '01.01.1901'
end
return #Retruns
end
if anyone gets a better idea???
Best regards
Oliver

Using the result of a subquery in a CASE expression with T-SQL

I'm writing a query with some CASE expressions and it outputs helper-data columns which help me determine whether or not a specific action is required. I would like to know if I can somehow use the result of a subquery as the output without having to perform the same query twice (between WHEN (subquery) THEN and as the result after THEN)
The dummy code below describes what I'm after. Can this be done? I'm querying a MS2005 SQL database.
SELECT 'Hello StackOverflow'
,'Thanks for reading this question'
,CASE
WHEN
(
SELECT count(*)
FROM sometable
WHERE condition = 1
AND somethingelse = 'value'
) > 0 THEN
-- run the query again to get the number of rows
(
SELECT count(*)
FROM sometable
WHERE condition = 1
AND somethingelse = 'value'
)
ELSE 0
END
SELECT 'Hello StackOverflow'
,'Thanks for reading this question'
,CASE
WHEN
(
SELECT count(*)
FROM sometable
WHERE condition = 1
AND somethingelse = 'value'
) AS subqry_count > 0 THEN
-- use the subqry_count, which fails... "Incorrect syntax near the keyword 'AS'"
subqry_count
ELSE 0
END
Just use the subquery as the source you are selecting from:
SELECT 'Hello StackOverflow'
,'Thanks for reading this question'
,CASE subqry_count.Cnt
WHEN 0 THEN 0
ELSE subqry_count.Cnt
END
FROM ( SELECT count(*) AS Cnt
FROM sometable
WHERE condition = 1
AND somethingelse = 'value'
) subqry_count
As an aside, if you are just going to return 0 if the output from COUNT is 0, then you don't even need to use a CASE statement.

How to put where clause for multiple columns while updating multiple columns at the same time?

I want to update more than 10 columns at the same time , and my problem is I want to put where clause for all these columns.
My code is:
UPDATE Customer AS c
SET
name = a.name,
address= a.address,
telephone = a.telephone,
--
--
--
FROM Customer a
INNER JOIN
( SELECT casenumber
, max(currentDate) AS md
FROM Customer
GROUP BY casenumber
) AS z
ON z.casenumber = a.casenumber
AND z.md = a.currentDate
WHERE (a.casenumber = c.casenumber)
In the above statement I want to add condition as to update columns only when they are not 0.
for exmple,
UPDATE Customer AS C
SET name = a.name,
address= a.address,
...
..
WHERE a.name <> 0,
a.address <> 0,
a.telephone <> 0
....
...
Is it possible to put where condition to check each column?
Any suggestions are appreciated..
Something like this (assuming name <> 0 is a typo and your names are really character columns)
UPDATE customer AS c
SET name = CASE WHEN name <> '' THEN a.name ELSE name END,
address = CASE WHEN address <> '' THEN a.address ELSE address END
This essentially updates the column to it's current value if it's empty.
Note that this does not deal with NULL values! If you need to treat NULL and '' identically you need to use coalesce(name, '') instead.

using CASE in T-SQL in the where clause?

Im trying to use case to vary the value im checking in a where clause but I'm getting the error:
incorrect syntax near the keyword 'CASE'
SQL Server 2005
select *
from table
where ((CASE when adsl_order_id like '95037%'
then select '000000'+substring(adsl_order_id,6,6)
ELSE select adsl_order_id
END)
not in (select mwebID from tmp_csv_dawis_bruger0105)
Here is one way to include a case statement in a Where clause:
SELECT * FROM sometable
WHERE 1 = CASE WHEN somecondition THEN 1
WHEN someothercondition THEN 2
ELSE ... END
You could try
SELECT *
FROM table
WHERE (SELECT CASE WHEN adsl_order_id LIKE '95037%'
THEN '000000' + SUBSTRING(adsl_order_id, 6, 6)
ELSE adsl_order_id
END)
NOT IN (select mwebID from tmp_csv_dawis_bruger0105)
A correlated subquery is one possibility:
select *
from mytable
where not exists (
select *
from
tmp_csv_dawis_bruger0105
where
mwebID =
CASE when mytable.adsl_order_id like '95037%' then '000000' + substring(mytable.adsl_order_id,6,6)
ELSE mytable.adsl_order_id END
)
I came to this question looking for an answer thinking WHERE CASE ... would be the solution. I could not adapt the answers to my problem, but this technique to use a parameter that could be null, partial, or specific, works:
CREATE PROC myproc #vJobID VARCHAR (11)
AS
SELECT * FROM Jobs
WHERE Jobs.JobID like coalesce(#vJobID+'%','%')
HTH
You have one too many opening parentheses before the CASE expression.
Put it in the SELECT clause...
select *, (CASE when adsl_order_id like '95037%'
then '000000'+substring(adsl_order_id,6,6)
ELSE adsl_order_id
END) AS Id
from table
where not in (select mwebID from tmp_csv_dawis_bruger0105)
Also, you don't need to "SELECT" the result of the CASE.