How to write if else condition in sql - mysql

In the following sql, how can i add if-else like control structure.
SELECT
tblcabbooking.id AS id,
concat(tblcabstatus.`status`,' ',
ifnull(concat("(INR",tblbookingcharges.totalbill,")"),'')) AS `status`,
tblcomplaint.id AS com_id,
tblcomplaint.statusid AS com_status,
tblcabbooking.csr_id AS emp,
concat(tblcabbooking.dropaddress,tblcabbooking.droparea) AS drop_area,
tblbookingcharges.totalbill,
tblcabbooking.booking_reference AS ref,
tblmasterpackage.master_package AS booking_type,
concat(tblcabbooking.pickupdate," ",tblcabbooking.pickuptime) AS ordertime,
concat(tblclient.clientname," ",tblappid.`type`) AS partner,
concat(tblcablistmgmt.NAME,', ',tbldriver.firstname,"(",tbldriver.contactno,")") AS vehicle,
concat(tbluserinfo.firstname,"(",tbluserinfo.mobno,")") AS clientname,
concat(tbldriver.firstname," ",tbldriver.contactno) AS driver_name,
tblcabbooking.mobileno AS mob_no,
tbluserinfo.uid AS client_id,
tbldriver.uid AS driver_id,
concat(tblcabbooking.pickupaddress,' ',tblcabbooking.pickuparea) AS departure,
tbldriver.vehicleregistrationno AS reg
FROM tblcabbooking
JOIN tblcabstatus
ON tblcabbooking.`status`=tblcabstatus.`status_id`
JOIN tbluserinfo
ON tbluserinfo.uid=tblcabbooking.clientid
JOIN tblmasterpackage
ON tblcabbooking.bookingtype=tblmasterpackage.package_id
LEFT JOIN tbldriver
ON tblcabbooking.pickup=tbldriver.uid
LEFT JOIN tblcablistmgmt
ON tbldriver.typeofvehicle=tblcablistmgmt.id
JOIN tblappid
ON tblappid.id=tblcabbooking.partner
JOIN tblclient
ON tblappid.clientid=tblclient.id
LEFT JOIN tblbookingcharges
ON tblcabbooking.id=tblbookingcharges.bookingid
LEFT JOIN tblcomplaint
ON tblcabbooking.id=tblcomplaint.bookingid
WHERE tblcabbooking.bookingdate >= fromdate
AND tblcabbooking.bookingdate <= todate
AND tblcabbooking.mobileno=ifnull(callerid,tblcabbooking.mobileno)
AND tblcabbooking.booking_reference=ifnull(book_ref, tblcabbooking.booking_reference)
AND tbldriver.vehicleregistrationno=ifnull(vehicle_number, tbldriver.vehicleregistrationno)
AND tbldriver.firstname=ifnull(vehicle_driver, tbldriver.firstname)IF partnertype LIKE 'Android Booking' then
AND
tblcabbooking.devicetype='ANDROID'
ELSE
IF partnertype LIKE 'Web Booking' then
AND
tblcabbooking.devicetype='WEB'
ELSE
IF partnertype LIKE 'Call Center Booking' then
AND
tblcabbooking.devicetype='0'
ELSE
and
partnertype=tblcabbooking.devicetype
END
IF ORDER BY tblcabbooking.id DESC ;

NO, you can't use IF .. ELSE construct in normal ANSI SQL query, but you can rewrite it using CASE statement like
WHERE tblcabbooking.devicetype =
CASE WHEN partnertype LIKE 'Android Booking'
THEN 'ANDROID' ELSE 'Web Booking'

Related

how to use SELECT CASE in sql statment with MySql

I have the next sql statment, I want to check value of xxx:
if xxx=1 then "good1"
if xxx=2 then "good2"
if xxx=3 then "good3"
if xxx=4 then "good4"
if xxx=5 then "good5"
SELECT
xRef, xPar, AccID, AccLevel, AccType, LEFT(AccCode,1) AS xxx
FROM (
SELECT Parent_AccRef AS xRef, Parent_ParentID AS xPar FROM tblaccountsparents
union ALL
SELECT AccRef AS xRef, AccID AS xPar FROM tblaccounts WHERE AccType<>'final' AND AccParent<>0) xtbl
INNER JOIN tblaccounts ON tblaccounts.AccRef = xtbl.xRef
how to use the select case here, I saw many solutions here but not correct for my case.
If the value always 1-5, then how about just creating the string you want using CONCAT():
SELECT xRef, xPar, AccID, AccLevel, AccType,
CONCAT('good', LEFT(AccCode,1)) AS whatever
If the value can be something else, then you can add a CASE expression:
SELECT xRef, xPar, AccID, AccLevel, AccType,
(CASE WHEN LEFT(AccCode, 1) BETWEEN '1' AND '5'
THEN LEFT(CONCAT('good', LEFT(AccCode, 1))
END) AS whatever
SELECT
xRef, xPar, AccID, AccLevel, AccType, LEFT(AccCode,1) AS xxx,
CASE
WHEN LEFT(AccCode,1)='1' THEN 'GOOD1'
WHEN LEFT(AccCode,1)='2' THEN 'GOOD2'
WHEN LEFT(AccCode,1)='3' THEN 'GOOD3'
WHEN LEFT(AccCode,1)='4' THEN 'GOOD4'
ELSE 'SOMETHING ELSE'
END AS FLAG
FROM (
SELECT Parent_AccRef AS xRef, Parent_ParentID AS xPar FROM tblaccountsparents
union ALL
SELECT AccRef AS xRef, AccID AS xPar FROM tblaccounts WHERE AccType<>'final' AND AccParent<>0
) xtbl
INNER JOIN tblaccounts ON tblaccounts.AccRef = xtbl.xRef

How would I constrain my CONCAT statement to just the id from the if statement in MySQL

I've been beating my head against the wall for a while now on this. I've tried following the thought behind Concat in If statement but I can't seem to figure out a way to make my specific need work. I'm now down to a syntax error in my CONCAT statement..'WHERE req.reqCreatedBy = '0' THEN 'Unknown' ELSE users.firstname,' ',users.lastn'. Could anybody give me some help on bringing the first and last name in on this query? I'm at a complete loss.
SELECT req.reqID as Id,
reqDesc.titleText as Title,
req.reqCity as City,
req.reqState as State,
req.areaID as Area,
area.areaname,
reqType.typeTitle as Type,
req.reqCreatedDate as Created,
req.reqEndDate as `End`,
CONCAT((CASE WHERE req.reqCreatedBy = '0' THEN 'Unknown' ELSE users.firstname,' ',users.lastname END))
AS Recruiter
FROM apps_job_request as req
INNER JOIN apps_job_request_description as reqDesc
ON req.reqTitle = reqDesc.titleID
INNER JOIN apps_job_request_type as reqType
ON reqDesc.typeID = reqType.typeID
INNER JOIN `assemble_users`.area AS area
ON area.areaid = req.areaID
INNER JOIN `assemble_users`.users AS users
ON users.username = req.reqCreatedBy
WHERE req.reqID is not null
AND req.reqActive = '1'
If check only one value req.reqCreatedBy, there may be simple IF statement, use CASE for multiple checked values.
SELECT req.reqID as Id,
reqDesc.titleText as Title,
req.reqCity as City,
req.reqState as State,
req.areaID as Area,
area.areaname,
reqType.typeTitle as Type,
req.reqCreatedDate as Created,
req.reqEndDate as `End`,
-- req.reqCreatedBy is '0' OR ''?
IF(req.reqCreatedBy = '0', 'Unknown', CONCAT(users.firstname, ' ', users.lastname)) AS Recruiter
FROM apps_job_request as req
INNER JOIN apps_job_request_description as reqDesc
ON req.reqTitle = reqDesc.titleID
INNER JOIN apps_job_request_type as reqType
ON reqDesc.typeID = reqType.typeID
INNER JOIN `assemble_users`.area AS area
ON area.areaid = req.areaID
INNER JOIN `assemble_users`.users AS users
ON users.username = req.reqCreatedBy
WHERE req.reqID is not null
AND req.reqActive = '1'

MYSQL insert multiple row from select statement

I have results from select statement,but i need to insert the result into another table.How to archieve this on mysql or php?
Select statement :
SELECT a.*,MONTH(bd.tarikh) bulan,tahun
FROM
(
SELECT bl_ic_pesawah ic,bl_name name,bl_musim musim,bl_zon_id zon,bl_nettWeight nettWeight,
CASE
WHEN bl_nettWeight BETWEEN be_rangef AND be_ranget THEN be_quantity
WHEN bl_nettWeight >= be_morethan THEN be_quantity_1
WHEN bl_nettWeight = be_morethan_sws THEN be_quantity_sws
ELSE NULL END AS layak,
be.be_date_from date_from,be_date_to date_to
FROM b_ledger
LEFT JOIN b_entitle be ON bl_musim = be_season AND bl_zon_id = be_zid
WHERE be.be_status='Buka' AND bl_id = 1
) a
LEFT JOIN b_date bd ON bd.tarikh BETWEEN a.date_from AND a.date_to
GROUP BY MONTH(bd.tarikh),a.ic
After inserted into table it will be something like this:
You could use select in insert query, With your task:
INSERT INTO other_table (ic ,name ,musim ,zon ,nettWeight ,layak ,date_from ,date_to)
SELECT a.ic ,a.name ,a.musim ,a.zon ,a.nettWeight ,a.layak ,a.date_from ,a.date_to
,MONTH(bd.tarikh) bulan,tahun
FROM
(
SELECT bl_ic_pesawah ic,bl_name name,bl_musim musim,bl_zon_id zon,bl_nettWeight nettWeight,
CASE
WHEN bl_nettWeight BETWEEN be_rangef AND be_ranget THEN be_quantity
WHEN bl_nettWeight >= be_morethan THEN be_quantity_1
WHEN bl_nettWeight = be_morethan_sws THEN be_quantity_sws
ELSE NULL END AS layak,
be.be_date_from date_from,be_date_to date_to
FROM b_ledger
LEFT JOIN b_entitle be ON bl_musim = be_season AND bl_zon_id = be_zid
WHERE be.be_status='Buka' AND bl_id = 1
) a
LEFT JOIN b_date bd ON bd.tarikh BETWEEN a.date_from AND a.date_to
GROUP BY MONTH(bd.tarikh),a.ic
Get the result into an array.. then opening another database connection to create a new table..then INSERT sql using new database_table_name

MYSQL database IFNULL query

I'm trying to display a 'NULL' value as 0 using 'IFNULL' but it returns all rows as null or 0. Everything works fine until I add the 'lounge2' table and the 'lounge2order2' table. The order2.lounge2orderid is 'NULL'. I know it has something to do with 'JOINS' but not sure where or which to implement.
Thanks all...
SELECT orders2.orderid, orders2.orderdate, branch2.branchname, COUNT(orders2.garment2orderid) AS 'no gar orders', SUM(garment2.hireprice) as 'total gar sold',
COUNT(orders2.lounge2orderid+IFNULL(orders2.lounge2orderid,0)) as 'No of lounge sales', SUM(lounge2.hirerate)
from orders2, branch2, garment2, garment2order2, lounge2, lounge2order2
WHERE orders2.orderid IN
(SELECT orders2.orderid FROM orders2
WHERE orders2.branchid = 2
AND YEAR(orders2.orderdate)= 2011)
AND branch2.branchid IN
(SELECT branch2.branchid from branch2
WHERE branch2.branchid = orders2.branchid)
AND garment2order2.garment2orderid IN
(SELECT garment2order2.garment2orderid FROM garment2order2
WHERE garment2order2.garment2orderid = orders2.garment2orderid)
AND garment2.garmentid IN
(SELECT garment2.garmentid FROM garment2
WHERE garment2.garmentid = garment2order2.garmentid)
AND lounge2order2.lounge2orderid IN
(SELECT lounge2order2.lounge2orderid FROM lounge2order2
WHERE lounge2order2.lounge2orderid = orders2.lounge2orderid)
AND lounge2.loungeid IN
(SELECT lounge2.loungeid FROM lounge2
WHERE lounge2.loungeid = lounge2order2.loungeid)
First of all, try to avoid FROM orders2, branch2, garment2, garment2order2, lounge2, lounge2order2 it must be JOIN ... ON statement. That would help you to debug and us to understand what your logic and table relations are.
And to have any agregate functions like SUM or COUNT working you should set GROUP BY statement.
Since I have no idea what is your database structure like.
Here is my try:
SELECT
orders2.orderid,
orders2.orderdate,
COUNT(orders2.garment2orderid) AS 'no gar orders',
branch2.branchname,
SUM(garment2.hireprice) as 'total gar sold',
SUM(IF(orders2.lounge2orderid IS NULL,1,0)) as 'No of lounge sales',
SUM(lounge2.hirerate)
FROM orders2
LEFT JOIN branch2
ON branch2.branchid = orders2.branchid
LEFT JOIN garment2order2
ON garment2order2.garment2orderid = orders2.garment2orderid
LEFT JOIN garment2
ON garment2.garmentid = garment2order2.garmentid
LEFT JOIN lounge2order2
ON lounge2order2.lounge2orderid = orders2.lounge2orderid
LEFT JOIN lounge2
ON lounge2.loungeid = lounge2order2.loungeid)
WHERE orders2.branchid = 2
AND YEAR(orders2.orderdate)= 2011
GROUP BY orders2.orderid

Error when trying to join a view in linq-to-sql

While trying to extract data from a view by joining it with two other tables, I'm getting the following error: "SQL Server does not handle comparison of NText, Text, Xml, or Image data types."
And here is the query:
var expeditions = from VE in context.ViewExpeditions
join SIAGR in context.SiteInAdviseGoodsRef on VE.DeliveryNotes equals SIAGR.Value
join SIA in context.SiteInAdvise on SIAGR.SiteInAdviseId equals SIA.Id
where SIA.Id == SiteInAdviseID
select VE;
Here is the View ViewExpeditions:
SELECT ve.*, S.[$Refex] as SiteRefex,c.[$Refex] as ServiceRefex , DeliveryNotes = LEFT(o.list, LEN(o.list)-1),st.Status,st.StatusRefex
from(
SELECT
B.[$Id] AS Booking,
B.[$Refex] AS BookingRefex,
B.SiguxCPUE AS CartaDePorte,
SUM(ISNULL(BG.Weight, 0)) AS Weight,
SUM(ISNULL(BG.Volume, 0)) AS Volume,
ISNULL( SUBSTRING(B.Comments, 1, 100),'') AS Comments,
'Type' =
CASE
WHEN PickupSite IS NULL THEN 'Pickup'
ELSE 'Delivery'
END,
'Name' =
CASE
WHEN PickupSite IS NULL THEN PickupName
ELSE DeliveryName
END,
'City' =
CASE
WHEN PickupSite IS NULL THEN PickupCity
ELSE DeliveryCity
END,
'PostalCode' =
CASE
WHEN PickupSite IS NULL THEN PickupPostalCode
ELSE DeliveryPostalCode
END,
'ContactName' =
CASE
WHEN PickupSite IS NULL THEN ISNULL(B.PickupContactName,'')
ELSE ISNULL(B.DeliveryContactName,'')
END,
'ContactPhone' =
CASE
WHEN PickupSite IS NULL THEN ISNULL(B.PickupContactPhone,'')
ELSE ISNULL( B.DeliveryContactPhone,'')
END,
B.PickupDate AS DataExp,
B.DeliveryDate,
coalesce( B.PickupSite,B.DeliverySite) as 'Site',
b.Service,isnull(B.SiguxState,0) as SiguxState
FROM dbo.BookingGoods AS BG
INNER JOIN dbo.Booking AS B ON BG.BookingId = B.[$Id]
WHERE (B.ExecutedBy = 2) AND B.SiguxCPUE is not null AND B.[$IsDeleted]=0
GROUP BY B.PickupCity,b.PickupContactName,b.PickupContactPhone,b.PickupName,b.PickupPostalCode, B.DeliveryName,B.DeliverySite, B.DeliveryCity, B.DeliveryPostalCode, B.DeliveryContactName, B.DeliveryContactPhone, B.PickupDate, B.[$Id], B.SiguxCPUE, B.[$Refex], B.Comments,b.PickupSite,B.Service,B.SiguxState,B.DeliveryDate
) ve
INNER join [ViewBookingActualStatus] st on st.Booking=ve.Booking
INNER join Service c on ve.Service=c.[$Id]
INNER JOIN dbo.Site AS S ON S.[$Id] = ve.Site
outer APPLY
(
SELECT distinct
CONVERT(VARCHAR(12), dbo.BookingGoodsRef.Value) + ', ' AS [text()]
FROM
dbo.BookingGoodsRef
WHERE
dbo.BookingGoodsRef.BookingId = ve.Booking and BookingGoodsRef.Type=13
FOR XML PATH('')
) o (list)
Where am I going wrong about this?
NOTE: If I try to run the query in linqpad, it doesn't give me any errors at all, and generates the following sql:
SELECT [t0].[Booking], [t0].[BookingRefex], [t0].[CartaDePorte], [t0].[Weight], [t0].[Volume], [t0].[Comments], [t0].[Type], [t0].[Name], [t0].[City], [t0].[PostalCode], [t0].[ContactName], [t0].[ContactPhone], [t0].[DataExp], [t0].[DeliveryDate], [t0].[Site], [t0].[Service], [t0].[SiguxState], [t0].[SiteRefex], [t0].[ServiceRefex], [t0].[DeliveryNotes], [t0].[Status], [t0].[StatusRefex]
FROM [ViewExpeditions] AS [t0]
INNER JOIN [SiteInAdviseGoodsRef] AS [t1] ON [t0].[DeliveryNotes] = [t1].[Value]
INNER JOIN [SiteInAdvise] AS [t2] ON [t1].[SiteInAdviseId] = [t2].[$Id]
WHERE [t2].[$Id] = #p0
If you copy the generated SQL from LinqPad into SSMS and try to run it, do you get the results you expect?
I'd guess that the one of the columns on which you're joining (probably DeliveryNotes) is ntext or text. SQL Server can't join on text columns - you have to either cast both columns to varchar or use a substring on both columns.