select-where clause outs different results - sql-server-2008

I got this query in my SQL Server 2008 procedure
insert into tableXYZ(ID, CODPROY, NOMPROY, TITOBS, OBSERVACION, RECOMENDACION, RESPUESTA, UNIDRESP, CONTACTO, FECHAEMISION, RIESGO, ULTIMAACTUALIZACION, FECHAVENCIMIENTO, ESTADO, FECHACARGATC, REGULADOR, REGULADO)
select
ID_Obs, CodigoProyecto, NombreProyecto, TituloObservacion, Incidencia,
Recomendacion, Respuesta, UnidadResponsable, Propietario,
case when isdate(FechaEmision) = 1 then CONVERT(DATETIME, FechaEmision, 103) end,
Riesgo, EstadoActualizacion,
case when isdate(FechaRevisada) = 1 then (CONVERT(DATETIME, FechaRevisada, 103)) else (case when isdate(FechaEstimada) = 1 then CONVERT(DATETIME,FechaEstimada,105) end) end,
Estado,
case when isdate(FechaCargaTC) = 1 then CONVERT(DATETIME, FechaCargaTC, 103) end,
Grupo, 'BCPPE'
from
#myTableType
where
GRUPO <> '467' and GRUPO <> '912' and GRUPO <> '910' and GRUPO <> ''
As you can see this query has many cast methods, the problem is that the results of this sentence is so differente between two users. Can you give me some clues?
PD: Look this part:
case when isdate(FechaRevisada) = 1 then (CONVERT(DATETIME, FechaRevisada, 103))
else (case when isdate(FechaEstimada) = 1 then CONVERT(DATETIME, FechaEstimada, 105) end)
end
This part of the query works right with me, but do not with my partner.

Related

mysql date range query, when the field is not sent anything for the 'between' statement

I have this query, which returns me 7 records
Now if I add this line 'AND date_format (ds.date_emission,'% Y-% m-% d ') BETWEEN' 'AND' '', nothing returns me, I want that when the date range is empty I need that I also returned the 7 records
Please refer answer below.
I have added two variable replace inStartDate variable with a range start date and inEndDate with range end date.
SELECT ds.id
FROM documentos_salida ds
WHERE ds.terceros_id = 329
AND ds.estado =0
AND ds.tipo_documento ='Factura'
AND ds.saldo_pendiente_factura >0
AND (ds.fecha_vencimiento > now() or
ds.fetcha_vencimiento = NOW())
AND ds.numero_documento LIKE '%%'
AND ( CASE WHEN (inStartDate = '' AND inEndDate = '')
THEN TRUE
ELSE (date_format(ds.fetcha_emision, '%Y-%m-%d') BETWEEN inStartDate AND inStartDate)
END)
ORDER BY ds.fecha_emision DESC;

Why is alias not allowed in GROUP BY in MySQL? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Referring to a Column Alias in a WHERE Clause
SELECT
Trade.TradeId,
Isnull(Securities.SecurityType,'Other') SecurityType,
TableName,
CASE
WHEN
SecurityTrade.SecurityId IS NOT NULL
THEN
SecurityTrade.SecurityId
ELSE
Trade.SecurityId
END AS PricingSecurityID,
sum(Trade.Quantity)OVER(Partition by Securities.SecurityType, SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity,
--added porfolio id for Getsumofqantity
Trade.PortfolioId,
Trade.Price,
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position
from
Fireball_Reporting..Trade
where porfolioid =5 and Position =1
i want to use Position =1 in my where clause which is an alias of case
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position
How can I use it in where clause?
I tried zo directly use that CASE statement in where clause, but failed.
WHERE Trade.SecurityId = #SecurityId AND PortfolioId = #GHPortfolioID AND
(case when (Buy = 1 and Long = 1) then 1 when (Buy = 0 and Long = 0) then 1 else 0 end Position = 1)
The SQL-Server docs says:
column_alias can be used in an ORDER BY clause, but it cannot be used in a WHERE, GROUP BY, or HAVING clause.
Similar in the MySQL doc it says:
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.
In MySQL you can at least reuse aliases in the SELECT clause
You can't, not directly.
If you wrap the whole query in a sub-query, however, it works fine.
SELECT
*
FROM
(
SELECT
Trade.TradeId,
Isnull(Securities.SecurityType,'Other') SecurityType,
TableName,
CASE
WHEN SecurityTrade.SecurityId IS NOT NULL THEN SecurityTrade.SecurityId
ELSE Trade.SecurityId
END AS PricingSecurityID,
sum(Trade.Quantity)OVER(Partition by Securities.SecurityType,
SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity,
--added porfolio id for Getsumofqantity
Trade.PortfolioId,
Trade.Price,
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position
from
Fireball_Reporting..Trade
where
porfolioid = 5
)
AS data
WHERE
Position = 1
This means that you don't need to repeat the CASE statement in WHERE clause. (Maintainable and DRY).
It is also a structure that allows the optimiser to behave as if you had simply repeated yourself in the WHERE clause.
It's also very portable to other RDBMSs.
In SQL Server, then you also have another option...
SELECT
Trade.TradeId,
Isnull(Securities.SecurityType,'Other') SecurityType,
TableName,
CASE
WHEN SecurityTrade.SecurityId IS NOT NULL THEN SecurityTrade.SecurityId
ELSE Trade.SecurityId
END AS PricingSecurityID,
sum(Trade.Quantity)OVER(Partition by Securities.SecurityType,
SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity,
--added porfolio id for Getsumofqantity
Trade.PortfolioId,
Trade.Price,
position.val AS Position
from
Fireball_Reporting..Trade
CROSS APPLY
(
SELECT
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end AS val
)
AS position
where
porfolioid = 5
AND position.val = 1
You can't directly do this...but you can wrap an additional select around it all and use the where clause:
select * from
( SELECT
Trade.TradeId,
Isnull(Securities.SecurityType,'Other') SecurityType,
TableName,
CASE
WHEN
SecurityTrade.SecurityId IS NOT NULL
THEN
SecurityTrade.SecurityId
ELSE
Trade.SecurityId
END AS PricingSecurityID,
sum(Trade.Quantity)OVER(Partition by Securities.SecurityType, SecurityTrade.SecurityId,Trade.Price, Buy,Long ) as sumQuantity,
--added porfolio id for Getsumofqantity
Trade.PortfolioId,
Trade.Price,
case
when (Buy = 1 and Long = 1) then 1
when (Buy = 0 and Long = 0) then 1
else 0
end Position
from
Fireball_Reporting..Trade
where porfolioid =5 and Position =1
)x
where x.position = 1
I'm probably missing something but surely this will cover it:
WHERE (Buy = 1 and Long = 1) OR (Buy = 0 and Long = 0)

Syntax error in case statement while creating MySQL view

I am getting mysql #1064 error while trying to create a view
CREATE VIEW trip_summary AS select `driver_details`.`DriverId`, CONCAT(driver_details.Firstname, ' ', driver_details.Lastname, ' ', driver_details.TaxiPlateNo) AS TaxiDriver, count(taxi_trip.AutoId) AS TotalTrip, GROUP_CONCAT(taxi_trip.AutoId) AS TripIds, sum(taxi_trip.TripDistance) AS TotalTripDistance, sum(taxi_trip.TotalFare) AS TotalTripFare from `driver_details` left join `taxi_trip` on (`taxi_trip`.`DriverId` = `driver_details`.`DriverId` and `taxi_trip`.`PickupLAT` != 0 and `taxi_trip`.`DropLAT` != 0 and `taxi_trip`.`TotalFare` != 0) where taxi_trip.AutoId!=0 and
CASE WHEN `DriverIdFun`()!='' THEN taxi_trip.DriverId = `DriverIdFun`()
END AS field1,
CASE WHEN `From_Date`()!='' THEN taxi_trip.RequestDate >= `From_Date`()
END AS field2,
CASE WHEN `To_Date`()!='' THEN taxi_trip.RequestDate <= `To_Date`()
END AS field3 group by taxi_trip.DriverId
This isn't a complete answer, but may contain enough info to get you started....
Typically (but not everytime), a VIEW into a set of database tables does not have a WHERE clause, and in your case the WHERE clause looks like a dog's breakfast.
I'd start with this much simpler view and develop from here....
CREATE VIEW trip_summary AS
SELECT
dd.`DriverId`,
CONCAT(dd.Firstname, ' ', dd.Lastname, ' ', dd.TaxiPlateNo) AS TaxiDriver,
count(tt.AutoId) AS TotalTrip,
GROUP_CONCAT(tt.AutoId) AS TripIds,
sum(tt.TripDistance) AS TotalTripDistance,
sum(tt.TotalFare) AS TotalTripFare
FROM `driver_details` AS dd
LEFT JOIN `taxi_trip` AS tt
ON tt.`DriverId` = dd.`DriverId`
AND tt.`PickupLAT` != 0
AND tt.`DropLAT` != 0
AND tt.`TotalFare` != 0
GROUP BY tt.DriverId
Then when you query the view, you select what you do and don't want out of the view by means of the where clause
SELECT * FROM trip_summary WHERE DriverID=1234;
This is the correct query to create the view which i need
CREATE VIEW trip_summary AS
select
`driver_details`.`DriverId`,
CONCAT(driver_details.Firstname, ' ', driver_details.Lastname, ' ',
driver_details.TaxiPlateNo) AS TaxiDriver,
count(taxi_trip.AutoId) AS TotalTrip,
GROUP_CONCAT(taxi_trip.AutoId) AS TripIds,
sum(taxi_trip.TripDistance) AS TotalTripDistance,
sum(taxi_trip.TotalFare) AS TotalTripFare
from `driver_details`
left join `taxi_trip`
on (`taxi_trip`.`DriverId` = `driver_details`.`DriverId`
and `taxi_trip`.`PickupLAT` != 0
and `taxi_trip`.`DropLAT` != 0
and `taxi_trip`.`TotalFare` != 0)
where taxi_trip.AutoId!=0
and
CASE
WHEN `DriverIdFun`()!=''
THEN taxi_trip.DriverId = `DriverIdFun`()
ELSE
TRUE
END
AND
CASE
WHEN `From_Date`()!=''
THEN taxi_trip.RequestDate >= `From_Date`()
ELSE
TRUE
END
AND
CASE
WHEN `To_Date`()!=''
THEN taxi_trip.RequestDate <= `To_Date`()
ELSE
TRUE
END
group by taxi_trip.DriverId

Getting error with CASE expression using WHERE clause

declare #SP nvarchar(3)
SELECT HDR.SOPNUMBE, HDR.docdate, HDR.pymtrmid,
RTRIM(HDR.ShipToName) +
CASE WHEN HDR.ADDRESS1 <> '' THEN char(10) + RTRIM(HDR.ADDRESS1) ELSE '' END
FROM vSOPHdr HDR
WHERE HDR.SOPTYPE = 2 AND
(CASE WHEN HDR.SLPRSNID <> 'All'
then HDR.SLPRSNID in (''+#SP+'')
else HDR.SLPRSNID between '0' and 'ZZZZZZZZZZZZZZZ'
end)
I am trying to run the above query in sql query analyzer but getting 'syntax' errors in the CASE expression (near IN, ELSE). What could be wrong?
All I want to do is when sales-personID is selected as ALL in the report parameter I would like to process all sales person else only the selected sales person ID.
Just a background about what I am doing,
I have a similar query to the above query (without the CASE condition) within a dataset for a SSRS report.
Note that #SP is a report parameter.
CASE is an expression that returns a single value. It cannot be used for control-of-flow logic, like in other languages such as VB. Try:
WHERE HDR.SOPTYPE = 2 AND
((HDR.SLPRSNID <> 'All' AND HDR.SLPRSNID = #SP)
OR
(HDR.SLPRSNID = 'All'))
Though it seems like maybe you need instead, which would make more logical sense if the user is potentially passing 'All' into the parameter:
WHERE HDR.SOPTYPE = 2 AND
((#SP <> 'All' AND HDR.SLPRSNID = #SP)
OR
(#SP = 'All'))
you can just use an OR clause
WHERE HDR.SOPTYPE = 2 AND
((HDR.SLPRSNID <> 'All' AND HDR.SLPRSNID IN (''+#SP+''))
OR
(HDR.SLPRSNID = 'All' AND HDR.SLPRSNID BETWEEN '0' and 'ZZZZZZZZZZ'))
Not sure if the BETWEEN '0' and 'ZZZZZZZZZZZ' means "IN everything". If yes, you can just remove it now.
If you absolutely wanna use a CASE WHEN, you can do it this way :
WHERE HDR.SOPTYPE =2
AND (CASE WHEN HDR.SLPRSNID <>'All' AND HRD.SLPRSNDID IN (''+#SP+'')) THEN 1
WHEN HDR.SLPRSNID = 'All' AND HDR.SLPRSNID BETWEEN '0' and 'ZZZZZZZZZZ' THEN 1
ELSE 0
END) = 1

MySQL SELECT calculation subject to stricter criteria than other SELECT fields--how?

Previously, the following query was limited based on work_category_id. Turns out we need information from as subclass of another work_category_id, so now I'm limiting on job_code_id instead. Job_code_id 29 is work_category_id 88, all other job_code_ids shown are work_category_id 36.
I need hours and performance for each of these job_code_ids, but specifically for the 'cases_per_hr' calculation, I only want to divide cases by all hours except those from job_code_id 29. I tried a nested case when, but that didn't seem to make much sense. Please help!
SELECT
d.user_id as 'employee_ID',
round((sum(d.goal_hours)/sum(d.worked_hours)),2)*100 as 'performance',
round(sum(d.goal_hours),2) as 'goal_hrs',
round(sum(d.worked_hours),2) as 'hrs_worked',
sum(d.cases) as 'total_cases_slctd',
round(sum(d.cases)/sum(d.worked_hours),0) as 'cases_per_hr',
d.metric_dt
FROM
roster r,
prod_detail d
WHERE
d.process_level = r.process_level
and d.accounting_unit = r.accounting_unit
and d.job_code_id in ('29','322','304','303','302','305','181')
-- and d.work_category_id in('36')
If you only want to exclude job_code_id = '29' from your cases_per_hr calculation, you could do the following. It does use CASE WHEN.
SELECT d.user_id as 'employee_ID',
round((sum(d.goal_hours)/sum(d.worked_hours)),2)*100 as 'performance',
round(sum(d.goal_hours),2) as 'goal_hrs',
round(sum(d.worked_hours),2) as 'hrs_worked',
sum(d.cases) as 'total_cases_slctd',
round(
sum(CASE WHEN d.job_code_id <> '29' THEN d.cases ELSE 0 END)
/
sum(CASE WHEN d.job_code_id <> '29' THEN d.worked_hours ELSE 0 END)
,0) as 'cases_per_hr',
d.metric_dt
FROM roster r,
prod_detail d
WHERE
d.process_level = r.process_level
and d.accounting_unit = r.accounting_unit
and d.job_code_id in ('29','322','304','303','302','305','181')