How to insert my MySQL Case When Statement into PHP using PDO so I can add the output to my column chart - pdo

I am working on a Column Chart and want to add the values of my MySQL Case When Statement into the chart. However, I need help to write the statement in PHP using PDO so I can integrate it into my application's column chart.How can I write the Case When Statement into PHP using PDO?
SELECT
COUNT(CASE WHEN tbl_projects.projsector = 'Agriculture' THEN 1 END) AS `AG`,
COUNT(CASE WHEN tbl_projects.projsector = 'Building Construction' THEN 1 END) AS `BC`,
COUNT(CASE WHEN tbl_projects.projsector = 'Health' THEN 1 END) AS `HT`,
COUNT(CASE WHEN tbl_projects.projsector = 'Education' THEN 1 END) AS `ED`,
COUNT(CASE WHEN tbl_projects.projsector = 'Water Supply' THEN 1 END) AS `WS`,
COUNT(CASE WHEN tbl_projects.projsector = 'Income Generation' THEN 1 END) AS `IG`,
COUNT(tbl_projects.projsector) AS 'Total SEctors',
concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Agriculture' THEN 1 END)/COUNT(tbl_projects.projsector) * 100 )) AS '% AG',
concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Building Construction' THEN 1 END)/COUNT(tbl_projects.projsector) * 100)) AS '% BC',
concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Health' THEN 1 END)/COUNT(tbl_projects.projsector) * 100)) AS '% HT', concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Education' THEN 1 END)/COUNT(tbl_projects.projsector) * 100 )) AS '% ED',
concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Water Supply' THEN 1 END)/COUNT(tbl_projects.projsector) * 100)) AS '% WS',
concat(round(COUNT(CASE WHEN tbl_projects.projsector = 'Income Generation' THEN 1 END)/COUNT(tbl_projects.projsector) * 100)) AS '% IG'
FROM tbl_projects
My expected result is supposed to look like this
AG BC HT ED WS IG TotalSEctors %AG %BC %HT %ED %WS %IG
2 1 0 2 3 0 8 25 13 0 25 38 0
Thank you in advance

Thanks to everyone who attempted to provide help to my question. I finally got solution to my question. I am going to post the code I used below.
Now there are 2 aspect of values that I needed for my chart. The first are Normal COUNT values as seen below from AG to IG and the second are Percentage values as seen from %AG to %IG.
AG BC HT ED WS IG TotalSEctors %AG %BC %HT %ED %WS %IG
2 1 0 2 3 0 8 25 13 0 25 38 0
To generate this values from the table, I digged online and found some codes on how to COUNT values in MySQL using PDO Prepared Statement. After studying the codes, I was able to write mine as seen below
<?php
//database connection
include('Connections/db.php');
//create a function for count
function rowCount($connect,$query){
$stmt = $connect->prepare($query);
$stmt->execute();
return $stmt->rowCount();
}
?>
With this line of codes, I was able to count records and then generate the percentage.
<h1> Agriculture = `<?php echo (rowCount($connect,"SELECT projsector AS '% AG' FROM
tbl_projects WHERE projsector = 'Agriculture' ") / rowCount($connect,"SELECT
projsector FROM tbl_projects ")) * 100; ?>` </h1>
<h1> Building Construction = `<?php echo (rowCount($connect,"SELECT projsector AS '%
AG' FROM tbl_projects WHERE projsector = 'Building Construction' ") /
rowCount($connect,"SELECT projsector FROM tbl_projects ")) * 100; ?> </h1>
<h1> Health = `<?php echo (rowCount($connect,"SELECT projsector AS '% AG' FROM
tbl_projects WHERE projsector = 'Health' ") / rowCount($connect,"SELECT projsector
FROM tbl_projects ")) * 100; ?>` </h1>
<h1> Education = `<?php echo (rowCount($connect,"SELECT projsector AS '% AG' FROM
tbl_projects WHERE projsector = 'Education' ") / rowCount($connect,"SELECT
projsector FROM tbl_projects ")) * 100; ?>` </h1>
<h1> Water Supply = `<?php echo (rowCount($connect,"SELECT projsector AS '% AG' FROM
tbl_projects WHERE projsector = 'Water Supply' ") / rowCount($connect,"SELECT
projsector FROM tbl_projects ")) * 100; ?>` </h1>
<h1> Income Generation = `<?php echo (rowCount($connect,"SELECT projsector AS '% AG'
FROM tbl_projects WHERE projsector = 'Income Generation' ") /
rowCount($connect,"SELECT projsector FROM tbl_projects ")) * 100; ?>` </h1>
OUTPUT
Agriculture = 25%
Building Construction = 12.5%
Health = 0%
Education = 25%
Water Supply = 37.5%
Income Generation = 0%
For Normal COUNT Values with no percentage, I use these codes
Agriculture = <?php echo rowCount($connect,"SELECT projsector AS '% AG' FROM
tbl_projects WHERE projsector = 'Agriculture' "); ?>
Building Construction = <?php echo rowCount($connect,"SELECT projsector AS '% BC'
FROM tbl_projects WHERE projsector = 'Building Construction' "); ?>
Health = <?php echo rowCount($connect,"SELECT projsector AS '% HT' FROM tbl_projects
WHERE projsector = 'Health' "); ?>
Education = <?php echo rowCount($connect,"SELECT projsector AS '% ED' FROM
tbl_projects WHERE projsector = 'Education' "); ?>
Water Supply = <?php echo rowCount($connect,"SELECT projsector AS '% WS' FROM
tbl_projects WHERE projsector = 'Water Supply' "); ?>
Income Generation = <?php echo rowCount($connect,"SELECT projsector AS '% IG' FROM
tbl_projects WHERE projsector = 'Income Generation' "); ?>
I trust someone will find these useful

Related

SQL Error [905] [42000]: ORA-00905: missing keyword when use case when in oracle

I'm using oracle to calculate some column in table
this is my LOG0104M table:
PRODUCT_CODE PRODUCT_NAME PRODUCT_CAT TOTAL_QUANTITY PACKING_STYLE
112677 AP-1516D AP 65 30
my recipe:
FULLBOX = TOTAL_QUANTITY / PACKING_STYLE
SPARE_QUANTITY = TOTAL_QUANTITY - FULLBOX * PACKING_STYLE
condition:
if SPARE_QUANTITY = 0 => SPARE_QUANTITY = 0
if SPARE_QUANTITY >=1 => SPARE_QUANTITY = 1
my query:
SELECT
L04.TOTAL_QUANTITY
, L04.PRODUCT_CODE
, L04.PRODUCT_NAME
, CASE WHEN
SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) = 0
THEN
SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) = 0
ELSE
SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) >= 1
THEN
SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) = 1
END
END AS SPARE_QUANTITY
, L04.PRODUCT_CAT
FROM
LOG0104M L04
When I run my query, I get this error:
SQL Error [905] [42000]: ORA-00905: missing keyword
How can I fix the problem? Many thanks
The problem with your query is the ELSE statement being used as an if/else You should useCASE in your query like this:
SELECT L04.TOTAL_QUANTITY
,L04.PRODUCT_CODE
,L04.PRODUCT_NAME
,CASE
WHEN SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) = 0 THEN 0
WHEN SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE) >= 1 THEN 1
ELSE SUM(L04.TOTAL_QUANTITY - (L04.TOTAL_QUANTITY / L04.PACKING_STYLE) * L04.PACKING_STYLE)
END AS SPARE_QUANTITY
,L04.PRODUCT_CAT
FROM LOG0104M L04
GROUP BY L04.TOTAL_QUANTITY
,L04.PRODUCT_CODE
,L04.PRODUCT_NAME
,L04.PRODUCT_CAT
,L04.PACKING_STYLE

I am getting an SQLCODE=-119 in DB2

I was converting MySql to DB2 queries, and so far I got to this:
SELECT
loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM
(
SELECT
cl.display_name AS clientName,
cl.id AS clientId,
ln.id AS loanId,
ln.account_no AS accountId,
ln.loan_status_id AS accountStatusId,
pl.short_name AS productShortName,
ln.product_id AS productId,
ln.currency_code AS currencyCode,
ln.currency_digits AS currencyDigits,
ln.currency_multiplesof AS inMultiplesOf,
rc.name AS currencyName,
rc.display_symbol AS currencyDisplaySymbol,
rc.internationalized_name_code AS currencyNameCode,
CASE WHEN ln.loan_status_id = 200 THEN ln.principal_amount
ELSE NULL
END AS disbursementAmount,
SUM(COALESCE((CASE WHEN ln.loan_status_id = 300 THEN ls.principal_amount ELSE 0.0 END), 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.principal_completed_derived ELSE 0.0 END, 0.0)) AS principalDue,
ln.principal_repaid_derived AS principalPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_completed_derived ELSE 0.0 END, 0.0)) AS interestDue,
ln.interest_repaid_derived AS interestPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_completed_derived ELSE 0.0 END, 0.0)) AS feeDue,
ln.fee_charges_repaid_derived AS feePaid
FROM
m_loan LN
JOIN m_client cl ON
cl.id = ln.client_id
LEFT JOIN m_office OF ON
of.id = cl.office_id
AND of.hierarchy LIKE ?
LEFT JOIN m_product_loan pl ON
pl.id = ln.product_id
LEFT JOIN m_currency rc ON
rc.code = ln.currency_code
JOIN m_loan_repayment_schedule ls ON
ls.loan_id = ln.id
AND ls.completed_derived = 0
AND ls.duedate <= ?
WHERE
of.id = ?
AND (ln.loan_status_id = 300)
AND ln.group_id IS NULL
) AS loandata
LEFT JOIN m_loan_charge lc ON
lc.loan_id = loandata.loanId
AND lc.is_paid_derived = 0
AND lc.is_active = 1
AND ( lc.due_for_collection_as_of_date <= ?
OR lc.charge_time_enum = 1)
GROUP BY
loandata.clientId,
loandata.loanId
ORDER BY
loandata.clientId,
loandata.loanId
But I am getting an error :
SQL Error [42803]: An expression starting with "DISBURSEMENTAMOUNT"
specified in a SELECT clause, HAVING clause, or ORDER BY clause is not
specified in the GROUP BY clause or it is in a SELECT clause, HAVING
clause, or ORDER BY clause with a column function and no GROUP BY
clause is specified.. SQLCODE=-119, SQLSTATE=42803, DRIVER=4.26.14
I have tried inserting Group by and Order By clauses each for the select clause items like so:
SELECT
loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM
(
SELECT
cl.display_name AS clientName,
cl.id AS clientId,
ln.id AS loanId,
ln.account_no AS accountId,
ln.loan_status_id AS accountStatusId,
pl.short_name AS productShortName,
ln.product_id AS productId,
ln.currency_code AS currencyCode,
ln.currency_digits AS currencyDigits,
ln.currency_multiplesof AS inMultiplesOf,
rc.name AS currencyName,
rc.display_symbol AS currencyDisplaySymbol,
rc.internationalized_name_code AS currencyNameCode,
CASE WHEN ln.loan_status_id = 200 THEN ln.principal_amount
ELSE NULL
END AS disbursementAmount,
SUM(COALESCE((CASE WHEN ln.loan_status_id = 300 THEN ls.principal_amount ELSE 0.0 END), 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.principal_completed_derived ELSE 0.0 END, 0.0)) AS principalDue,
ln.principal_repaid_derived AS principalPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.interest_completed_derived ELSE 0.0 END, 0.0)) AS interestDue,
ln.interest_repaid_derived AS interestPaid,
SUM(COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_amount ELSE 0.0 END, 0.0) - COALESCE(CASE WHEN ln.loan_status_id = 300 THEN ls.fee_charges_completed_derived ELSE 0.0 END, 0.0)) AS feeDue,
ln.fee_charges_repaid_derived AS feePaid
FROM
m_loan LN
JOIN m_client cl ON
cl.id = ln.client_id
LEFT JOIN m_office OF ON
of.id = cl.office_id
AND of.hierarchy LIKE ?
LEFT JOIN m_product_loan pl ON
pl.id = ln.product_id
LEFT JOIN m_currency rc ON
rc.code = ln.currency_code
JOIN m_loan_repayment_schedule ls ON
ls.loan_id = ln.id
AND ls.completed_derived = 0
AND ls.duedate <= ?
WHERE
of.id = ?
AND (ln.loan_status_id = 300)
AND ln.group_id IS NULL
GROUP BY
cl.display_name,
cl.id,
ln.id,
ln.account_no,
ln.loan_status_id,
pl.short_name,
ln.product_id,
ln.currency_code,
ln.currency_digits,
ln.currency_multiplesof,
rc.name,
rc.display_symbol,
rc.internationalized_name_code,
ln.loan_status_id,
ln.principal_amount,
ln.principal_repaid_derived,
ln.interest_repaid_derived,
ln.fee_charges_repaid_derived
ORDER BY
cl.display_name,
cl.id,
ln.id,
ln.account_no,
ln.loan_status_id,
pl.short_name,
ln.product_id,
ln.currency_code,
ln.currency_digits,
ln.currency_multiplesof,
rc.name,
rc.display_symbol,
rc.internationalized_name_code,
ln.loan_status_id,
ln.principal_amount,
ln.principal_repaid_derived,
ln.interest_repaid_derived,
ln.fee_charges_repaid_derived
) AS loandata
LEFT JOIN m_loan_charge lc ON
lc.loan_id = loandata.loanId
AND lc.is_paid_derived = 0
AND lc.is_active = 1
AND ( lc.due_for_collection_as_of_date <= ?
OR lc.charge_time_enum = 1)
GROUP BY
loandata.clientId,
loandata.loanId
ORDER BY
loandata.clientId,
loandata.loanId
A gross simplification of your query is:
SELECT loandata.*,
SUM(lc.amount_outstanding_derived) AS chargesDue
FROM (SELECT <lots of columns>
FROM <lots of tables>
. . .
) loandata LEFT JOIN
m_loan_charge lc
ON lc.loan_id = loandata.loanId AND
lc.is_paid_derived = 0 AND
lc.is_active = 1 AND
( lc.due_for_collection_as_of_date <= ? OR lc.charge_time_enum = 1)
GROUP BY loandata.clientId, loandata.loanId
ORDER BY loandata.clientId, loandata.loanId;
You have a SELECT * bringing in lots of columns. Fine. Then you have an aggregation function -- so the query is an aggregation query. Need a GROUP BY with lots of columns.
But I don't find one. I only find a GROUP BY with two columns. And that is an error in SQL. And happily, that is now an error in the more recent versions of MySQL. And in basically every other database.
You need to list all the columns in the GROUP BY that are not aggregated in the SELECT.

SQL query taking longer time to execute

I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-
SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup, VNC.productcomponent,
VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
VNC.[high %], VNC.vqi, VNC.deepcontrol,
--Modification done for CHE10045964
PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
SFG_ProductNo = CASE
WHEN UCHSC.attribute_ != P.productno
THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
RC.Name as ResourceClassName
FROM order_header OH
INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
INNER JOIN dbo. product P ON WO.productid = P.id
INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
WHERE OH.ordertype = 23
GROUP BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
CASE
WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
--Added By Sukanya Biswas(CHE10045964)
NC.WorkCenter
FROM (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
[LowUnits] = Isnull(b.[1], 0),
[Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
ELSE Isnull(b.[1], 0)
END, [HighUnits] = Isnull(b.[2], 0),
[High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
ELSE Isnull(b.[2], 0)
END ,
--Added By Sukanya Biswas(CHE10045964)
B.WorkCenter
FROM (SELECT D .orderno, SampleID = DTS.id,
--Added By Sukanya Biswas(CHE10045964)
DL.WorkCenter,
Comment = CASE Isnull(DTS.comment_, '')
WHEN '' THEN 'N/A'
ELSE DTS.comment_
END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
NC.weightingfactor, NC.ConsumerSensitive,
Severity = Isnull(QD.qualitydefectseverityid, 0),
QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
FROM dbo.disposition D
INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
--Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
AND DT.linesequenceno = DL.linesequenceno
INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
WHERE DL.linecode = 'VQ'
) A
PIVOT (Sum(a.noofdefects)
FOR severity IN ([1],[2]))
B)
NC
As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.
You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017"

SubQuery within SUM CASE AND IN Conditions

I have this query blow.
SELECT DISTINCT
'CONTRACT',
CO.OBJID,
CO.ORDERNUMBER
(SELECT SUM(CASE WHEN CT.SHORTNAME = 'BGL'
THEN TG.QUANTITY
ELSE 0 END) AS Cartons,
SUM(CASE WHEN CT.SHORTNAME = 'CT'
THEN TG.QUANTITY
ELSE 0 END) AS Boxes,
SUM(CASE WHEN CT.SHORTNAME = 'PL'
THEN TG.QUANTITY
ELSE 0 END) AS Trailer
FROM GOODS TG,
XTYPE CT
WHERE TG.ORDERID = CO.OBJID
AND TG.CONTOBJECTID = CT.OBJID
AND CT.SHORTNAME IN ('BGL', 'CT', 'PL')
)
FROM XCUSTORDER CO,
XEDIPARTNER EP
WHERE CIP.CUSTOID = CO.OBJECTID
AND CO.EDIPARTNER_OBJECTID = EP.OBJECTID
AND EP.ILNNUMBER = 'NASA'
The query is not working how can I achive the result I need. I dont want to run a diffrent select for each of the Cartons, Boxes and Trailer
TRY THIS: if you want to do all in single query. You have to query separately for each column as below. I am not sure that it will work because it's not tested but I am sure it will give you good idea. You are joining with CIP.CUSTOID but the table with CIP alias is not mentioned anywhere in the query so I did EP in the second query.
SELECT DISTINCT
'CONTRACT',
CO.OBJID,
CO.ORDERNUMBER,
(SELECT SUM(TG.QUANTITY)
FROM GOODS TG,
XTYPE CT
WHERE TG.ORDERID = CO.OBJID
AND TG.CONTOBJECTID = CT.OBJID
AND CT.SHORTNAME IN ('BGL')) AS Cartons,
(SELECT SUM(TG.QUANTITY)
FROM GOODS TG,
XTYPE CT
WHERE TG.ORDERID = CO.OBJID
AND TG.CONTOBJECTID = CT.OBJID
AND CT.SHORTNAME IN ('CT')) AS Boxes,
(SELECT SUM(TG.QUANTITY)
FROM GOODS TG,
XTYPE CT
WHERE TG.ORDERID = CO.OBJID
AND TG.CONTOBJECTID = CT.OBJID
AND CT.SHORTNAME IN ('PL')) AS Trailer
FROM XCUSTORDER CO,
XEDIPARTNER EP
WHERE CIP.CUSTOID = CO.OBJECTID
AND CO.EDIPARTNER_OBJECTID = EP.OBJECTID
AND EP.ILNNUMBER = 'NASA'
You can change your query in the following way:
SELECT
'CONTRACT',
CO.OBJID,
CO.ORDERNUMBER,
SUM(CASE WHEN CT.SHORTNAME = 'BGL'
THEN TG.QUANTITY
ELSE 0 END) AS Cartons,
SUM(CASE WHEN CT.SHORTNAME = 'CT'
THEN TG.QUANTITY
ELSE 0 END) AS Boxes,
SUM(CASE WHEN CT.SHORTNAME = 'PL'
THEN TG.QUANTITY
ELSE 0 END) AS Trailer
FROM XCUSTORDER CO
INNER JOIN XEDIPARTNER EP ON EP.CUSTOID = CO.OBJECTID
AND CO.EDIPARTNER_OBJECTID = EP.OBJECTID
AND EP.ILNNUMBER = 'NASA'
LEFT JOIN GOODS TG ON TG.ORDERID = CO.OBJID
LEFT JOIN XTYPE CT ON TG.CONTOBJECTID = CT.OBJID
AND CT.SHORTNAME IN ('BGL', 'CT', 'PL')
GROUP BY CO.OBJID,
CO.ORDERNUMBER

Case statement in where

I am writing a query to get all the invoices with amount > 100 for US > 200 for CAN and > 1200 for mxn ( mexico)
Invoice_Header table ( total amount and company id)
Company table (company id and currency id)
currency table ( currency id and currency)
SELECT IH.Invoice_Num , IH.invoice_amount , IH.invoice_date
FROM Invoice_Header IH ,
company c,
Currency cu
WHERE IH.Company_oid = c.Company_oid
AND c.currency_oid = cu.currency_oid
AND
CASE IH.total =
WHEN cu.code = 'USA' then IH.total > 100
WHEN cu.code = 'CAN' then IH.total > 200
WHEN cu.code = 'MXN' then IH.total > 1200
END
I am getting syntax errors when trying to run this on a oracle database.
I wouldn't use a CASE statement here. It sounds like you want some basic boolean logic
AND( (cu.code = 'USA' and ih.total > 100)
OR (cu.code = 'CAN' and ih.total > 200)
OR (cu.code = 'MXN' and ih.total > 1200))
If you really wanted to use a CASE statement for some reason, you could do something like
AND 1 = (CASE WHEN cu.code = 'USA' and ih.total > 100
THEN 1
WHEN cu.code = 'CAN' and ih.total > 200
THEN 1
WHEN cu.code = 'MXN' and ih.total > 1200
THEN 1
ELSE 0
END)
I would try something like
SELECT IH.Invoice_Num , IH.invoice_amount , IH.invoice_date
FROM Invoice_Header IH ,
company c,
Currency cu
WHERE IH.Company_oid = c.Company_oid
AND c.currency_oid = cu.currency_oid
AND ( (cu.code = 'USA' and IH.total > 100)
OR (cu.code = 'CAN') and IH.total > 100)
OR (cu.code = 'MXN') and IH.total > 1200))
if you really need to use a CASE in the where clause you could do something like
SELECT 'WEEK-END' AS col_a
FROM DUAL
WHERE 1 = CASE
WHEN to_char(sysdate, 'Day') = 'Saturday' then 1
WHEN to_char(sysdate, 'Day') = 'Sunday' then 1
else 0
END