I have a query for sales and i need to add item group property from OITG table. but couldn't find any direct link. I am a novice so really have no idea how to add Item group property in Below query. Please advise.
Select T0.[DocNum],
T0.[DocDate],
Case when T0.[ObjType] = 13 then 'INVOICE' when T0.[ObjType] = 14 then 'CREDIT NOTE' end as 'Type',
T0.[CardCode],
T0.[CardName],
T1.[ItemCode],
T1.[Dscription],
T1.[Quantity],
T0.[DocCur],
T1.[LineTotal] as 'Canadian,
Case when T1.[Rate] = 0 then T1.[LineTotal] else (T1.[LineTotal]/T1.[Rate]) end as 'Equivalent Value',
Case when (T1.[Quantity] = 0 and (T1.[StockPrice]*T1.[Quantity])= 0 ) then T1.[LineTotal] else (T1.[INMPrice]*T1.[Quantity]) end as 'Sales - Net',
(T1.[StockPrice]*T1.[Quantity]) as 'Cost',
T1.[GrssProfit],
Case when (T1.[INMPrice]*T1.[Quantity]) =0 then 0 else (T1.[GrssProfit]/(T1.[INMPrice]*T1.[Quantity]))*100 end as 'GP %age'
FROM
OINV T0 INNER JOIN INV1 T1 ON T0.[DocEntry] = T1.[DocEntry]
WHERE
T0.[CANCELED] = 'N' and
T0.[DocDate] >= [%0] and
T0.[DocDate] <=[%1] and
T1.[LineTotal] <> '0'
and i want to add a below subquery to above query.
src.ItemCode,src.ItemName,src.ItmsGrpNam
from
(select OITM.ItemCode,OITM.ItemName,OITG.ItmsGrpNam
from OITM CROSS JOIN OITG
where OITM.QryGroup1 = 'Y' and OITG.ItmsTypCod = 1
Select T0.[DocNum],
T0.[DocDate],
Case when T0.[ObjType] = 13 then 'INVOICE' when T0.[ObjType] = 14 then 'CREDIT NOTE' end as 'Type',
T0.[CardCode],
T0.[CardName],
T1.[ItemCode],
T1.[Dscription],
T1.[Quantity],
T0.[DocCur],
T1.[LineTotal] as 'Canadian',
Case when T1.[Rate] = 0 then T1.[LineTotal] else (T1.[LineTotal]/T1.[Rate]) end as 'Equivalent Value',
Case when (T1.[Quantity] = 0 and (T1.[StockPrice]*T1.[Quantity])= 0 ) then T1.[LineTotal] else (T1.[INMPrice]*T1.[Quantity]) end as 'Sales - Net',
(T1.[StockPrice]*T1.[Quantity]) as 'Cost',
T1.[GrssProfit],
Case when (T1.[INMPrice]*T1.[Quantity]) =0 then 0 else (T1.[GrssProfit]/(T1.[INMPrice]*T1.[Quantity]))*100 end as 'GP %age'
, T3.ItmsGrpNam
FROM OINV T0
INNER JOIN INV1 T1 ON T0.[DocEntry] = T1.[DocEntry]
INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
LEFT JOIN OITG T3 ON CASE WHEN ISNULL(T2.QryGroup1, '') = 'Y' THEN 1 WHEN ISNULL(T2.QryGroup2, '') = 'Y' THEN 2 END = ItmsTypCod
WHERE
T0.[CANCELED] = 'N' and
T0.[DocDate] >= [%0] and
T0.[DocDate] <=[%1] and
T1.[LineTotal] <> '0'
Related
The below code throws the following exception. How can I fix this?
Msg 8156, Level 16, State 1, Line 17
The column 'id' was specified multiple times for 'QISproduct'.
Query:
SELECT
g.artcode
, sum(g.aantal)
, i.class_01
, i.Isstockitem
FROM
gbkmut AS g
INNER JOIN
items AS i ON i.itemcode = g.artcode
INNER JOIN
(SELECT
QISP.id
, QISprocess.nml
, QISeventlog.id
, QISeventlog.dtsample
, QISproduct.nms
, QISbatchlog.nm
, QIStestlog.idvariable
, QIStestlog.no
, QISshortnote.ds
, gewicht = CASE QIStestlog.IDvariable
WHEN '139'
THEN QIStestlog.no
END
, aantal = CASE QIStestlog.IDvariable
WHEN '234'
THEN QIStestlog.no
END
, siloleeg = CASE QIStestlog.idvariable
WHEN '23'
THEN CASE QIStestlog.no
WHEN '10'
THEN 'Ja'
ELSE 'Nee'
END
END
, QISvariable.nml
, gl.nm
, QISprocess.id
FROM
QIC.Vobra_new2.dbo.production AS QISP
INNER JOIN
QIC.Vobra_new2.dbo.process AS QISprocess ON QISP.idprocess = QISProcess.id
INNER JOIN
QIC.Vobra_new2.dbo.product AS QISproduct ON QISP.idproduct = QISproduct.id
INNER JOIN
QIC.Vobra_new2.dbo.batchlog AS QISbatchlog ON QISP.idbatch = QISbatchlog.id
INNER JOIN
QIC.Vobra_new2.dbo.eventlog AS QISeventlog ON QISeventlog.idproduction = QISP.id
AND QISeventlog.idbatch = QISbatchlog.id
INNER JOIN
QIC.Vobra_new2.dbo.testlog AS QIStestlog ON QIStestlog.idevent = QISeventlog.id
LEFT OUTER JOIN
QIC.Vobra_new2.dbo.shortnote AS QISshortnote ON QISshortnote.id = QIStestlog.no
AND QIStestlog.idvariable = '144'
INNER JOIN
QIC.Vobra_new2.dbo.variable AS QISvariable ON QISvariable.id = QIStestlog.idvariable
LEFT OUTER JOIN
QIC.Vobra_new2.dbo.vvarxproc AS vvp ON vvp.idvariable = QISvariable.id
AND vvp.idprocess = QISP.idprocess
LEFT OUTER JOIN
QIC.Vobra_new2.dbo.attribute AS QISattribute ON QISattribute.id = vvp.idattribute
LEFT OUTER JOIN
QIC.Vobra_new2.dbo.grade AS QISgrade ON QISgrade.id = QISattribute.idgrade
LEFT OUTER JOIN
QIC.Vobra_new2.dbo.gradelevel AS gl ON gl.idgrade = QISattribute.idgrade
AND gl.nlevel = QIStestlog.no
WHERE
QISbatchlog.nm NOT LIKE 'V%'
AND QISP.dtstart > '2017-01-01'
AND QISP.dtstart < '2017-01-19'
AND QISP.idprocess IN ('12', '13', '14', '15', '16', '17', '18', '41')
AND QIStestlog.idvariable IN ('234', '139', '128')
) QISproduct ON g.artcode = QISproduct.nms
WHERE
g.bkjrcode > '2015'
AND g.reknr IN (3000, 3010, 3020)
AND g.aantal > 0
AND g.warehouse IN ('1', '9')
AND g.datum >= '2017-01-01'
AND g.oorsprong = 'R'
AND g.kstplcode <> 'VPR'
GROUP BY
g.artcode, i.Class_01, i.IsStockItem
The computed query aliased to QISProduct contains id column from two tables i.e. QISEventLog and QISProcess. So rename those columns to different names. Updated query
SELECT g.artcode
,sum(g.aantal)
,i.class_01
,i.Isstockitem
FROM gbkmut AS g
INNER JOIN items AS i ON i.itemcode = g.artcode
INNER JOIN (
SELECT QISP.id
,QISprocess.nml AS Processnml
,QISeventlog.id AS EventLogId
,QISeventlog.dtsample
,QISproduct.nms
,QISbatchlog.nm AS batchnm
,QIStestlog.idvariable
,QIStestlog.no
,QISshortnote.ds
,gewicht = CASE QIStestlog.IDvariable
WHEN '139'
THEN QIStestlog.no
END
,aantal = CASE QIStestlog.IDvariable
WHEN '234'
THEN QIStestlog.no
END
,siloleeg = CASE QIStestlog.idvariable
WHEN '23'
THEN CASE QIStestlog.no
WHEN '10'
THEN 'Ja'
ELSE 'Nee'
END
END
,QISvariable.nml variablenml
,gl.nm AS glnm
,QISprocess.id AS ProcessId
FROM QIC.Vobra_new2.dbo.production AS QISP
INNER JOIN QIC.Vobra_new2.dbo.process AS QISprocess ON QISP.idprocess = QISProcess.id
INNER JOIN QIC.Vobra_new2.dbo.product AS QISproduct ON QISP.idproduct = QISproduct.id
INNER JOIN QIC.Vobra_new2.dbo.batchlog AS QISbatchlog ON QISP.idbatch = QISbatchlog.id
INNER JOIN QIC.Vobra_new2.dbo.eventlog AS QISeventlog ON QISeventlog.idproduction = QISP.id
AND QISeventlog.idbatch = QISbatchlog.id
INNER JOIN QIC.Vobra_new2.dbo.testlog AS QIStestlog ON QIStestlog.idevent = QISeventlog.id
LEFT JOIN QIC.Vobra_new2.dbo.shortnote AS QISshortnote ON QISshortnote.id = QIStestlog.no
AND QIStestlog.idvariable = '144'
INNER JOIN QIC.Vobra_new2.dbo.variable AS QISvariable ON QISvariable.id = QIStestlog.idvariable
LEFT JOIN QIC.Vobra_new2.dbo.vvarxproc AS vvp ON vvp.idvariable = QISvariable.id
AND vvp.idprocess = QISP.idprocess
LEFT JOIN QIC.Vobra_new2.dbo.attribute AS QISattribute ON QISattribute.id = vvp.idattribute
LEFT JOIN QIC.Vobra_new2.dbo.grade AS QISgrade ON QISgrade.id = QISattribute.idgrade
LEFT JOIN QIC.Vobra_new2.dbo.gradelevel AS gl ON gl.idgrade = QISattribute.idgrade
AND gl.nlevel = QIStestlog.no
WHERE QISbatchlog.nm NOT LIKE 'V%'
AND QISP.dtstart > '2017-01-01'
AND QISP.dtstart < '2017-01-19'
AND QISP.idprocess IN (
'12'
,'13'
,'14'
,'15'
,'16'
,'17'
,'18'
,'41'
)
AND QIStestlog.idvariable IN (
'234'
,'139'
,'128'
)
) QISproduct ON g.artcode = QISproduct.nms
WHERE g.bkjrcode > '2015'
AND g.reknr IN (
3000
,3010
,3020
)
AND g.aantal > 0
AND g.warehouse IN (
'1'
,'9'
)
AND g.datum >= '2017-01-01'
AND g.oorsprong = 'R'
AND g.kstplcode <> 'VPR'
GROUP BY g.artcode
,i.Class_01
,i.IsStockItem
, QISbatchlog.nm
And
, gl.nm
Have same column name
You can add as to change colum name
, gl.nm as col1
You have multiple issues in your query. You are populating following columns with same column name in your inner query. Use Unique name using AS alias in inner query.
QISP.id
QISeventlog.id
QISprocess.id
gl.nm
QISbatchlog.nm
QISprocess.nml
QISvariable.nml
It is mandatory to have unique column name return by select list in sql.
So I apologize for the wall of code, but I'm losing my mind over this tiny issue that is kicking my butt. The below query works perfectly and gives me everything I need to see with the exception of one column from DB.ACTIVITY_T. The moment I add said column, I immediately get duplicates where there is a MNT.ARRIVEDTS present. I can't seem to figure out why adding one more column to my select statement is causing this duplication. Maybe I'm too deep into this to see what's right in front of me? If you see what could be causing the error, please feel free to enlighten me.
SELECT
TRIM(B.REFNUMBER) AS "REFNUMBER"
,DATE(NUM_TSTAMP) AS "P/U DATE"
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END AS "DELIVERY DATE"
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END AS "DELIVERED"
,B.WEIGHT AS "WGT"
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE) AS "SHPMNT CUBE"
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END AS "DERP POINT"
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO) END AS "DERP #"
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END AS "SEQUENCE"
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END AS "DERP DERP"
,DATE(E.EVENT_TIMESTAMP) AS "DERP DATE"
,TIME(E.EVENT_TIMESTAMP) AS "DERP TIME"
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END AS "DERP
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END AS "DERP CUBE”
,MNT."DERP ARRIVED"
FROM PQ.MAIN B
INNER JOIN PQ.MAIN_ALTERNATE A
ON B.REFNUMBER = A.REFNUMBER
AND B.CORRECTION = A.CORRECTION
AND A.NUMBER_KEY = ''
INNER JOIN PQ.MAIN_NAME C
ON C.REFNUMBER = B.REFNUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'
AND C.NUMBER_KEY = ''
AND C.NUM_CODE = 'ABCD'
INNER JOIN PQ.MAIN_NAME S
ON B.REFNUMBER = S.REFNUMBER
AND B.CORRECTION = S.CORRECTION
AND S.TYPE = 'S'
AND S.COUNTRY = 'US'
AND S.NUMBER_KEY = ''
LEFT OUTER JOIN DB.ACTIVITY_NUM MN
ON MN.REFNUMBER = B.REFNUMBER
LEFT OUTER JOIN (SELECT MAX(DATE(A.ARRIVEDTS)) AS "DERP ARRIVED", MFSTNBR
FROM AF.MANIFEST_T A WHERE A.DESTINATION IN ('1234','5647') GROUP BY MFSTNBR) AS MNT
ON MNT.MFSTNBR = MN.MFSTNBR
LEFT OUTER JOIN PQ.MAIN_EVENT E
ON E.REFNUMBER = B.REFNUMBER
AND E.EVENT_TYPE = 'R'
AND E.EVENT_DESCRIPTION = 'RANDO'
AND E.NUMBER_KEY = ''
LEFT OUTER JOIN DB.DERP_INDEX I
ON B.REFNUMBER = I.REFNUMBER
AND I.DOC_TYPE = 'LIE'
AND PAGE_NUM = '1'
AND I.INDEX_DATE >= CURRENT DATE - 15 DAYS
LEFT OUTER JOIN PQ.MAIN_REFNO R
ON R.REFNUMBER = B.REFNUMBER
AND R.CORRECTION = B.CORRECTION
AND REFNO LIKE '%BOOG%'
AND R.NUMBER_KEY = ''
WHERE B.NUM_NUM_NUM = '123'
AND B.DESTINATION IN ('1234','5647','9856')
AND DATE(B.NUM_TSTAMP) >= CURRENT DATE - 10 DAYS
GROUP BY
TRIM(B.REFNUMBER)
,DATE(NUM_TSTAMP)
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END
,B.WEIGHT
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE)
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO)
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END
,DATE(E.EVENT_TIMESTAMP)
,TIME(E.EVENT_TIMESTAMP)
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END
,MNT."DERP ARRIVED"
Here are the results that you asked for.
REFNUMBER DERP ARRIVED MFSTNBR
123456789 [null] [null]
123456789 [null] [null]
123456789 2015-12-15 32304587
987654321 [null] [null]
987654321 [null] [null]
987654321 2015-12-13 49304483
Each null actually has a different MFSTNBR tied to it, but it's returning a null because it doesn't meet the '1234' or '5647' criteria. If I remove the destination criteria the nulls would be replaced with similar but different MFSTNBR.
My guess is you're getting multiple records from MNT when you only want one...
Likely MNT.Destination having 2 different values will result in 2 records for the max, not one.
Replace the
LEFT OUTER JOIN DB.ACTIVITY_T MNT
with
(SELECT MAX(DATE(MNT.ARRIVEDTS)) as "DERP ARRIVED", MFSTNBR
FROM DB.Activity_T
WHERE MNT.DESTINATION IN ('1234','5647')
GROUP BY MFSTNBR) as MNT
and eliminate the join critiera;
ND MNT.DESTINATION IN ('1234','5647') as it's taken care of by the inline view.
oh and modify the select to just look for "DERP ARRIVED" on the top most select.
Just my guess...
SELECT
TRIM(B.REFNUMBER) AS "REFNUMBER"
,DATE(NUM_TSTAMP) AS "P/U DATE"
,CASE WHEN DATE(REPORT_TS) IS NULL THEN '' ELSE CHAR(DATE(REPORT_TS)) END AS "DELIVERY DATE"
,CASE WHEN REPORT_TS IS NULL THEN 'N' ELSE 'Y' END AS "DELIVERED"
,B.WEIGHT AS "WGT"
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE) AS "SHPMNT CUBE"
,CASE WHEN B.DESTINATION = '5647' THEN 'DERPO'
WHEN B.DESTINATION = '1234' THEN 'DERPB'
WHEN B.DESTINATION = '9856' THEN 'DERPC'
ELSE ''
END AS "DERP POINT"
,CASE WHEN R.REFNO IS NULL THEN '' ELSE CHAR(R.REFNO) END AS "DERP #"
,CASE WHEN C.CITY = 'DERPSTON' THEN 'BLAH'
WHEN C.CITY = 'DERPELVANIA' THEN 'HABD'
WHEN C.CITY = 'DERPVILLE' THEN 'POIN'
ELSE ''
END AS "SEQUENCE"
,CASE WHEN E.EVENT_DESCRIPTION = 'ABCD' THEN 'Y'
ELSE 'N'
END AS "DERP DERP"
,DATE(E.EVENT_TIMESTAMP) AS "DERP DATE"
,TIME(E.EVENT_TIMESTAMP) AS "DERP TIME"
,CASE WHEN I.DOC_TYPE = 'DERPI' THEN 'Y'
ELSE 'N'
END AS "DERP
,CASE WHEN B.CUBE > '0.5' THEN 'Y' ELSE 'N' END AS "DERP CUBE”
-------Modified the next line--------------
,MNT."DERP ARRIVED"
FROM PQ.MAIN B
INNER JOIN PQ.MAIN_ALTERNATE A
ON B.REFNUMBER = A.REFNUMBER
AND B.CORRECTION = A.CORRECTION
AND A.NUMBER_KEY = ''
INNER JOIN PQ.MAIN_NAME C
ON C.REFNUMBER = B.REFNUMBER
AND C.CORRECTION = B.CORRECTION
AND C.TYPE = 'C'
AND C.NUMBER_KEY = ''
AND C.NUM_CODE = 'ABCD'
INNER JOIN PQ.MAIN_NAME S
ON B.REFNUMBER = S.REFNUMBER
AND B.CORRECTION = S.CORRECTION
AND S.TYPE = 'S'
AND S.COUNTRY = 'US'
AND S.NUMBER_KEY = ''
LEFT OUTER JOIN DB.ACTIVITY_NUM MN
ON MN.REFNUMBER = B.REFNUMBER
-------Modified the next line--------------
LEFT OUTER JOIN (SELECT MAX(DATE(A.ARRIVEDTS)) as "DERP ARRIVED", MFSTNBR
FROM DB.Activity_T A
WHERE A.DESTINATION IN ('1234','5647')
GROUP BY MFSTNBR) as MNT
ON MNT.MFSTNBR = MN.MFSTNBR
-------Removed this line. the next line--------------
---and MNT.DESTINATION IN ('1234','5647') -------
LEFT OUTER JOIN PQ.MAIN_EVENT E
ON E.REFNUMBER = B.REFNUMBER
AND E.EVENT_TYPE = 'R'
AND E.EVENT_DESCRIPTION = 'RANDO'
AND E.NUMBER_KEY = ''
LEFT OUTER JOIN DB.DERP_INDEX I
ON B.REFNUMBER = I.REFNUMBER
AND I.DOC_TYPE = 'LIE'
AND PAGE_NUM = '1'
AND I.INDEX_DATE >= CURRENT DATE - 15 DAYS
LEFT OUTER JOIN PQ.MAIN_REFNO R
ON R.REFNUMBER = B.REFNUMBER
AND R.CORRECTION = B.CORRECTION
AND REFNO LIKE '%BOOG%'
AND R.NUMBER_KEY = ''
WHERE B.NUM_NUM_NUM = '123'
AND B.DESTINATION IN ('1234','5647','9856')
AND DATE(B.NUM_TSTAMP) >= CURRENT DATE - 10 DAYS
GROUP BY
TRIM(B.REFNUMBER)
,DATE(NUM_TSTAMP)
,REPORT_TS
,REPORT_TS
,B.WEIGHT
,B.PIECES
,B.WANT_DATE
,CEIL(B.CUBE)
,B.DESTINATION
,R.REFNO
,C.CITY
,E.EVENT_DESCRIPTION
,DATE(E.EVENT_TIMESTAMP)
,TIME(E.EVENT_TIMESTAMP)
,I.DOC_TYPE
,B.CUBE
--- Added this line----
,MNT."DERP ARRIVED"
I have the following code.
It has 2 dates:
1.
(case
when not trunc(iv.dated) is null then trunc(iv.dated) else trunc(iv1.dated)
end) date_stock_received
2.
trunc(dh.actshpdate) SHIP_DATE
Is there a way to join the dates so they show in one column?
select unique li.catnr, li.av_part_no,
(select sum(pl.qty_onhand) from part_loc pl where li.av_part_no = pl.part_no) qty_onhand,
(case
when not trunc(iv.dated) is null then trunc(iv.dated) else trunc(iv1.dated)
end) date_stock_received,
(case
when not sum(iv.quantity) is null then sum(iv.quantity) else sum(iv1.quantity)
end) qty_received,
dp.delqty, od.ord_extordnr, trunc(dh.actshpdate) SHIP_DATE
from leos_item li
LEFT JOIN scm_packtyp sp
ON li.packtyp = sp.packtyp
LEFT JOIN invtran_view_oes iv
ON li.av_part_no = iv.part_no
and (iv.transaction = 'NREC' and iv.location_no = ' RETURNS W')
LEFT JOIN invtran_view_oes iv1
on li.av_part_no = iv1.part_no
and (iv1.transaction = 'CORR+' and iv1.remark like 'STOCK FROM SP PALLET%')
LEFT JOIN oes_delsegview od
ON od.catnr = li.catnr
and od.prodtyp = li.prodtyp
and od.packtyp = li.packtyp
LEFT JOIN oes_dpos dp
ON od.ordnr = dp.ordnr
and od.posnr = dp.posnr
and od.segnr = dp.segnr
LEFT JOIN oes_dhead dh
on dp.dheadnr = dh.dheadnr
and dh.shpfromloc = 'W'
where li.cunr = '816900'
and substr(li.catnr,1,5) in ('RGMCD','RGJCD')
and li.item_type = 'FP'
and li.catnr = 'RGJCD221'
group by li.catnr, li.av_part_no, iv.dated, iv.quantity, iv1.dated, iv1.quantity, dp.delqty,
dp.ordnr, dp.posnr, dp.segnr, od.ord_extordnr, dh.actshpdate
order by li.av_part_no
Current result is ...
... what I would like to see is ...
Is this possible ?
The coalesce function might be what you want.
select trunc(coalesce(iv.dated, iv1.dated, dh.actshpdate)) theDateYouMightWant
I am receiving this error when trying to execute the query below. Any ideas or suggestions?
Error:
Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.
SELECT TestInstances.pkTestInstanceID AS 'pkTestInstanceID',
bands.pkPerformanceLevelReportBandID AS 'BandID',
bands.StackPosition AS 'StackPosition',
(SELECT TOP 100 PERCENT SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1 ELSE COUNT(StudentScores_Subject.pkStudentScoreID) END
FROM PerformanceLevelReportBands b
WHERE b.fkPerformanceLevelReportID = #intPerfLevelReportId
ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1 ELSE COUNT(StudentScores_Subject.pkStudentScoreID) END) AS 'Percent',
COUNT(StudentScores_Subject.pkStudentScoreID) AS 'Count'
FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR
((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR
(CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)))
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
ORDER BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
The problem is here you can't combine an outer and inner reference in an aggregate function
(SELECT TOP 100 PERCENT SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END
FROM PerformanceLevelReportBands b
WHERE b.fkPerformanceLevelReportID = #intPerfLevelReportId
ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END) AS 'Percent'
So change it to
(SELECT TOP 100 PERCENT SUM(CASE WHEN bb.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END
FROM PerformanceLevelReportBands b JOIN PerformanceLevelReportBands bb
ON bb.fkPerformanceLevelReportID =bands.fkPerformanceLevelReportID
AND b.fkPerformanceLevelReportID =bb.fkPerformanceLevelReportID
WHERE b.fkPerformanceLevelReportID = #intPerfLevelReportId
ORDER BY SUM(CASE WHEN bb.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100/ CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0 THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END) AS 'Percent'
Here is a more thorough explanation.
I'd recommend commenting out bandComponents then cutScores, rerunning after removing each components and seeing where the query fails. Once you figure out where it's failing, then you can fix it.
Also, could be this line, the query in your Percent column.
ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100
I tried to organize your query a bit better to make it more legible.
SELECT
TestInstances.pkTestInstanceID AS 'pkTestInstanceID'
, bands.pkPerformanceLevelReportBandID AS 'BandID'
, bands.StackPosition AS 'StackPosition'
, (
SELECT TOP 100 PERCENT
SUM( CASE
WHEN bands.StackPosition = b.StackPosition
THEN 1
ELSE 0
END) * 100 /
CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0
THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END
FROM PerformanceLevelReportBands b
WHERE b.fkPerformanceLevelReportID = #intPerfLevelReportId
ORDER BY SUM(CASE WHEN bands.StackPosition = b.StackPosition THEN 1 ELSE 0 END) * 100
/
CASE
WHEN COUNT(StudentScores_Subject.pkStudentScoreID) = 0
THEN 1
ELSE COUNT(StudentScores_Subject.pkStudentScoreID)
END
) AS 'Percent'
, COUNT(StudentScores_Subject.pkStudentScoreID) AS 'Count'
FROM
StudentScores_Subject
INNER JOIN
StudentTests ON
StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN
TestInstances ON
TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN
CAHSEE_TestPeriods ON
CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN
PerformanceLevelReportBands bands ON
bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN
MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON
cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN
PerfLevelReportBandComponents bandComponents ON
bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND(
(bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR
(
(CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore) OR
(CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore)
)
)
RIGHT JOIN
MM_SchoolYears ON
MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE
MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N','))
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
GROUP BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
ORDER BY TestInstances.pkTestInstanceID, bands.pkPerformanceLevelReportBandID, bands.StackPosition
I faced the same problem or something similar.
I left here both the initial code and the resolution in case it helps you.
Initial code:
SELECT ISNULL((SELECT DateName(mm,DATEADD(mm,Perioada - 1,0))),'Nedefinit') as [Period],MAX(t.TipPerioada) AS TipPerioada,t.Perioada,MAX(t.An) AS An, a.NumePrenume, CAST(t.Volum as float) as ValTip,
ISNULL((Select Sum(v.Cantitate*p.VolumProdus)
From Wme_Vanzari as v
WHERE ('ND'='ND' or v.MarcaAgent = t.MarcaAgent) and t.[An]=v.AnFactura and t.Perioada=v.Lunafactura),0) as Realizat,
'' as Diferenta,'' as DiferentaWD,'' as Procent
FROM [Memo_Target] t
--Aduce Suma de Cantitate si MarcaAgent pentru a nu dubla cu liniile din Vanzari
LEFT JOIN (Select SUM(Cantitate) as Cantitate, MarcaAgent
From Wme_Vanzari
WHERE AnFactura = #An
GROUP BY MarcaAgent) v on t.MarcaAgent = v.MarcaAgent
LEFT JOIN WME_Agenti a on a.Marca = t.MarcaAgent
--Aduce Suma de VolumProdus, CodProdus si Marca Agent Filtrat dupa Anul dat in parametru, Volum necesar pt a calcula Realizat si a scade din targetul setat
LEFT JOIN (SELECT SUM(ISNULL(n.VolumProdus, 0)) AS VolumProdus, v.CodProdus, v.MarcaAgent
FROM Wme_NomenclatorProduse n
LEFT JOIN Wme_Vanzari v ON v.CodProdus = n.CodIntern
WHERE v.MarcaAgent IS NOT NULL AND v.CodProdus IS NOT NULL AND v.AnFactura = #An
GROUP BY v.CodProdus, v.MarcaAgent ) p ON p.MarcaAgent = t.MarcaAgent
WHERE (t.Volum IS NOT NULL AND t.Volum > 0)
AND t.An = #An
AND (CAST(t.Perioada AS INT) BETWEEN #lunastart AND #lunaend)
AND TipTarget = #tiptarget
AND (a.Marca IN (SELECT * FROM dbo.GetIdsTableString(#marcaAgent)) OR #marcaAgent = 'ND')
GROUP BY a.NumePrenume, t.Volum, Perioada,t.An
Error message was the same, and this is the resolution code:
SELECT ISNULL((SELECT DateName(mm,DATEADD(mm,Perioada - 1,0))),'Nedefinit') as [Period],MAX(t.TipPerioada) AS TipPerioada,t.Perioada,MAX(t.An) AS An, a.NumePrenume, CAST(t.Volum as float) as ValTip,
(ISNULL((Select Sum(p.VolumProdus)
From Wme_Vanzari as v
WHERE ('ND'='ND' or v.MarcaAgent = t.MarcaAgent) and t.[An]=v.AnFactura and t.Perioada=v.Lunafactura),0) * sum(v.Cantitate)) as Realizat,
'' as Diferenta,'' as DiferentaWD,'' as Procent
FROM [Memo_Target] t
--Aduce Suma de Cantitate si MarcaAgent pentru a nu dubla cu liniile din Vanzari
LEFT JOIN (Select SUM(Cantitate) as Cantitate, MarcaAgent
From Wme_Vanzari
WHERE AnFactura = #An
GROUP BY MarcaAgent) v on t.MarcaAgent = v.MarcaAgent
LEFT JOIN WME_Agenti a on a.Marca = t.MarcaAgent
--Aduce Suma de VolumProdus, CodProdus si Marca Agent Filtrat dupa Anul dat in parametru, Volum necesar pt a calcula Realizat si a scade din targetul setat
LEFT JOIN (SELECT SUM(ISNULL(n.VolumProdus, 0)) AS VolumProdus, v.CodProdus, v.MarcaAgent
FROM Wme_NomenclatorProduse n
LEFT JOIN Wme_Vanzari v ON v.CodProdus = n.CodIntern
WHERE v.MarcaAgent IS NOT NULL AND v.CodProdus IS NOT NULL AND v.AnFactura = #An
GROUP BY v.CodProdus, v.MarcaAgent ) p ON p.MarcaAgent = t.MarcaAgent
WHERE (t.Volum IS NOT NULL AND t.Volum > 0)
AND t.An = #An
AND (CAST(t.Perioada AS INT) BETWEEN #lunastart AND #lunaend)
AND TipTarget = #tiptarget
AND (a.Marca IN (SELECT * FROM dbo.GetIdsTableString(#marcaAgent)) OR #marcaAgent = 'ND')
GROUP BY a.NumePrenume, t.Volum, Perioada,t.An
As you can see, I chose to leave a single column in the first subselect and i was forced to use multiplication operation after this subselect.
I hope it helps!
I've been trying to change this query. I don't want to use 'Not In' in this query. Can anybody help me how to change this query to left join query?
SELECT t.date,t.ticket,t.weight,t.Count, td.description
FROM tblticket t inner join tblticketdetails td on t.ticket = td.ticket
WHERE t.ticket NOT IN (SELECT r.Original_ticket from tblRenew R where isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid')
AND RTRIM(LTRIM(t.status)) = 'OPEN'
AND td.Type = 62
AND t.weight/t.Count >= 1000
AND t.date BETWEEN '2011-12-31' AND '2013-01-17'
Providing that you don't have multiple records in tblRenew for any ticket:
select
t.date, t.ticket, t.weight, t.Count, td.description
from
tblticket t
inner join tblticketdetails td on t.ticket = td.ticket
left join tblRenew R on isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid' and r.Original_ticket = t.ticket
where
r.Original_ticket is not null
and RTRIM(LTRIM(t.status)) = 'OPEN'
and td.Type = 62
and t.weight/t.Count >= 1000
and t.date BETWEEN '2011-12-31' AND '2013-01-17'
SELECT t.date, t.ticket,t.weight, t.Count, td.description
FROM tblticket t inner join
tblticketdetails td
on t.ticket = td.ticket left outer join
(SELECT r.Original_ticket
from tblRenew R
where isnull(r.new_ticket,'') = '' and
r.transaction_status = 'valid'
) v
on t.ticket = v.Original_ticket
WHERE t.ticket NOT IN (SELECT r.Original_ticket from tblRenew R where isnull(r.new_ticket,'') = '' and r.transaction_status = 'valid')
AND RTRIM(LTRIM(t.status)) = 'OPEN'
AND td.Type = 62
AND t.weight/t.Count >= 1000
AND t.date BETWEEN '2011-12-31' AND '2013-01-17'
and v.original_tiket is null