T-SQL Consolidate and merge two rows into one - sql

The goal is to have the Install Address and Dispatch address appear on the same line but I can't figure out a way of doing this. I am doing 2 queries on the same data and doing union all on the results. The address details may be different but also could be the same (eg Install and Dispatch address same).
Select zSTRI_CertificateNumber, CPS, InstallAdr1, InstallCity, DispAdr1, DispCity, DateSubmitted
From (
SELECT zSTRI_CertificateNumber,
'STRI' + CAST(op.ID as Varchar(4)) as CPSref,
JobRef,
CAST(CASE
WHEN notif.Cps = 1 THEN 'CPS'
END AS varchar(3)) as CPS,
notif.DateSubmitted,
nAdr.AddressLine1 as InstallAdr1,
nAdr.AddressLine2 as InstallAdr2,
nAdr.City as InstallCity,
nAdr.PostCode as InstallPostCode,
'' as DispAdr1,
'' as DispAdr2,
'' as DispCity,
'' as DispPostCode,
DateWorkCompleted,
c.CompanyName,
msrs.UniqueID
FROM [Notification] notif
INNER JOIN NotificationAddress nAdr
ON notif.ID = nAdr.NotificationID
INNER JOIN Company c
ON c.CompanyID = notif.CompanyID
INNER JOIN NotificationMeasures msrs
ON notif.ID = msrs.NotificationID
INNER JOIN Operative op
ON op.ID = NotifyingOperativeID
WHERE notif.DispatchMethodEmail = 0
AND nAdr.InstallAddress = 1
AND notif.ID = 5411
UNION ALL
SELECT zSTRI_CertificateNumber,
'STRI' + CAST(op.ID as Varchar(4)) as CPSref,
JobRef,
CAST(CASE
WHEN notif.Cps = 1 THEN 'CPS'
END AS varchar(3)) as CPS,
notif.DateSubmitted,
'' as InstallAdr1,
'' as InstallAdr2,
'' as InstallCity,
'' as InstallPostCode,
nAdr.AddressLine1 as DispAdr1,
nAdr.AddressLine2 as DispAdr2,
nAdr.City as DispCity,
nAdr.PostCode as DispPostCode,
DateWorkCompleted,
c.CompanyName,
msrs.UniqueID
FROM [Notification] notif
INNER JOIN NotificationAddress nAdr
ON notif.ID = nAdr.NotificationID
INNER JOIN Company c
ON c.CompanyID = notif.CompanyID
INNER JOIN NotificationMeasures msrs
ON notif.ID = msrs.NotificationID
INNER JOIN Operative op
ON op.ID = NotifyingOperativeID
WHERE
notif.DispatchMethodEmail = 0
AND nAdr.DispatchAddress = 1
AND notif.ID = 5411
) as SubGroup
Group by zSTRI_CertificateNumber, CPS, InstallAdr1, InstallCity, DispAdr1, DispCity, DateSubmitted

may be you are code is so huge as per my assumption and Use the MAX values for some NULL columns and Remove them in Group BY
SELECT
zSTRI_CertificateNumber,
CPS,
MAX(InstallAdr1) InstallAdr1,
InstallCity,
MAX(DispAdr1)DispAdr1,
MAX(DispCity)DispCity,
DateSubmitted
FROM (
SELECT zSTRI_CertificateNumber,
'STRI' + CAST(op.ID as Varchar(4)) as CPSref,
JobRef,
CAST(CASE
WHEN notif.Cps = 1 THEN 'CPS'
END AS varchar(3)) as CPS,
notif.DateSubmitted,
nAdr.AddressLine1 as InstallAdr1,
nAdr.AddressLine2 as InstallAdr2,
nAdr.City as InstallCity,
nAdr.PostCode as InstallPostCode,
'' as DispAdr1,
'' as DispAdr2,
'' as DispCity,
'' as DispPostCode,
DateWorkCompleted,
c.CompanyName,
msrs.UniqueID
FROM [Notification] notif
INNER JOIN NotificationAddress nAdr
ON notif.ID = nAdr.NotificationID
INNER JOIN Company c
ON c.CompanyID = notif.CompanyID
INNER JOIN NotificationMeasures msrs
ON notif.ID = msrs.NotificationID
INNER JOIN Operative op
ON op.ID = NotifyingOperativeID
WHERE notif.DispatchMethodEmail = 0
AND nAdr.InstallAddress = 1
AND notif.ID = 5411
UNION ALL
SELECT zSTRI_CertificateNumber,
'STRI' + CAST(op.ID as Varchar(4)) as CPSref,
JobRef,
CAST(CASE
WHEN notif.Cps = 1 THEN 'CPS'
END AS varchar(3)) as CPS,
notif.DateSubmitted,
'' as InstallAdr1,
'' as InstallAdr2,
'' as InstallCity,
'' as InstallPostCode,
nAdr.AddressLine1 as DispAdr1,
nAdr.AddressLine2 as DispAdr2,
nAdr.City as DispCity,
nAdr.PostCode as DispPostCode,
DateWorkCompleted,
c.CompanyName,
msrs.UniqueID
FROM [Notification] notif
INNER JOIN NotificationAddress nAdr
ON notif.ID = nAdr.NotificationID
INNER JOIN Company c
ON c.CompanyID = notif.CompanyID
INNER JOIN NotificationMeasures msrs
ON notif.ID = msrs.NotificationID
INNER JOIN Operative op
ON op.ID = NotifyingOperativeID
WHERE
notif.DispatchMethodEmail = 0
AND nAdr.DispatchAddress = 1
AND notif.ID = 5411
)As Subgroup
GROUP BY zSTRI_CertificateNumber, CPS, InstallCity, DateSubmitted

It sounds like you just need to join on the same NotificationAddress table twice within a single query, using different join criteria.
e.g.
select A.id, X.value as 'xValue', Y.value as 'yValue'
from IdTable A
inner join ValueTable X
on A.id=X.id
inner join ValueTable Y -- same table as "X"
on A.id=Y.id
where X.type = 'X'
and Y.type = 'Y' -- but different join criteria

Here is a summarised version of the query which does the job (based on the accepted answer)
Select NotifId, MAX(InstallAddress1) InstallAddress1,
MAX(InstallAddress2) InstallAddress2,
MAX(InstallCity) InstallCity,
MAX(InstallPostCode) InstallPostCode,
MAX(DispatchAddress1) DispatchAddress1,
MAX(DispatchAddress2) DispatchAddress2,
MAX(DispatchCity) DispatchCity,
MAX(DispatchPostCode) DispatchPostCode
FROM (
select X.NotificationID as NotifId,
X.AddressLine1 as 'InstallAddress1',
X.AddressLine2 as 'InstallAddress2',
X.City as 'InstallCity',
X.Postcode as 'InstallPostCode',
null as 'DispatchAddress1',
null as 'DispatchAddress2',
null as 'DispatchCity',
null as 'DispatchPostCode'
from NotificationAddress X
Where X.InstallAddress = 1
UNION
Select Y.NotificationID as NotifId,
null as 'InstallAddress1',
null as 'InstallAddress2',
null as 'InstallCity',
null as 'InstallPostCode',
Y.AddressLine1 as 'DispatchAddress1',
Y.AddressLine2 as 'DispatchAddress2',
Y.City as 'DispatchCity',
Y.Postcode as 'DispatchPostCode'
from NotificationAddress Y
where Y.DispatchAddress = 1
) as b
GROUP BY NotifId

Related

Invalid column in unpivot CTE query

I am getting the error Invalid column name MERCHANDISE_AMT'. on the below CTE unpivot query. I am selecting in MERCHANDISE_AMT in both queries so I do not understand why it's coming up as invalid. What am I overlooking here? If I take MERCHANDISE_AMT out of the unpivot than it runs, but I need to use this column for unpivoting. (unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
;WITH CTE AS (
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END AS LINE_TYPE , A.MERCHANDISE_AMT, CASE WHEN CONVERT(CHAR(24),A.QTY_VCHR) = '0' THEN '' ELSE B.QTY_VCHR END AS INVOICE_QTY, CASE WHEN CONVERT(CHAR(24),A.UNIT_PRICE) = '0' THEN '' ELSE A.UNIT_PRICE END AS UNIT_PRICE , A.UNIT_OF_MEASURE, REPLACE(A.DESCR,'"','') AS DESCR , '' AS BLANK1, '' AS BLANK2--A.PO_ID, A.LINE_NBR,
, ''AS BLANK3, ''AS BLANK4, --A.SCHED_NBR, B.PO_DIST_LINE_NUM,
''AS BLANK5,
''AS BLANK6,''AS BLANK7,''AS BLANK777,''AS BLANK8,''AS BLANK9,''AS BLANK10,''AS BLANK11,''AS BLANK12,
F.ORACLE_ENTITY + '.' + F.ORACLE_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '881' THEN '000'
WHEN B.BUSINESS_UNIT_GL = '14000' AND H.DEPTID = '889' THEN '950'
WHEN B.BUSINESS_UNIT_GL = '11000' AND H.DEPTID = '775' THEN '000'
WHEN B.DEPTID = '' THEN '000'
ELSE B.DEPTID END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000.' + '000000' AS SEGMENTS ,
''AS BLANK13, '2021/05/31' AS DATE1, ''AS BLANK14,''AS BLANK15,''AS BLANK16,''AS BLANK17, ''AS BLANK18, --A.SHIPTO_ID
''AS BLANK19,''AS BLANK199,''AS BLANK1999,''AS BLANK20,''AS BLANK21,''AS BLANK211,''AS BLANK22,''AS BLANK23,''AS BLANK24,''AS BLANK25,''AS BLANK26,''AS BLANK27,''AS BLANK28,''AS BLANK29,''AS BLANK30,''AS BLANK31,
''AS BLANK134,
''AS BLANK32, ''AS BLANK33, ''AS BLANK34, --A.SALETX_AMT --<--IS THIS THE RIGHT FIELD?
''AS BLANK35, ''AS BLANK36, --B.QTY_VCHR,
'N'AS BLANK37, ''AS BLANK38,''AS BLANK39,''AS BLANK40,''AS BLANK41,''AS BLANK411,''AS BLANK42, ''AS BLANK43, ''AS BLANK44,''AS BLANK45,''AS BLANK46,''AS BLANK47,''AS BLANK48,''AS BLANK49,''AS BLANK50,''AS BLANK51,''AS BLANK52,''AS BLANK53,''AS BLANK54,''AS BLANK55,''AS BLANK56,''AS BLANK57,''AS BLANK58,''AS BLANK59,''AS BLANK60,''AS BLANK61,''AS BLANK62,''AS BLANK63,''AS BLANK64,''AS BLANK65,''AS BLANK66,''AS BLANK67,''AS BLANK68,''AS BLANK69,''AS BLANK70,''AS BLANK71,''AS BLANK72,''AS BLANK73,''AS BLANK74,''AS BLANK75,''AS BLANK76,''AS BLANK77,''AS BLANK78,''AS BLANK79,''AS BLANK80,
''AS BLANK81,''AS BLANK82,''AS BLANK83,''AS BLANK84,''AS BLANK85,''AS BLANK86,''AS BLANK87,''AS BLANK88,''AS BLANK89,''AS BLANK90,''AS BLANK91,''AS BLANK92,''AS BLANK93,''AS BLANK94,''AS BLANK95,''AS BLANK96,''AS BLANK97,''AS BLANK98,''AS BLANK99,''AS BLANK100,''AS BLANK101,''AS BLANK102,''AS BLANK103,''AS BLANK104,''AS BLANK105,''AS BLANK106,''AS BLANK107,''AS BLANK108,''AS BLANK109,''AS BLANK110,''AS BLANK111,''AS BLANK112,''AS BLANK113,''AS BLANK114,''AS BLANK115,''AS BLANK116,''AS BLANK117,''AS BLANK118,''AS BLANK119,''AS BLANK120,''AS BLANK121,''AS BLANK122,''AS BLANK123,''AS BLANK124,''AS BLANK125,''AS BLANK126,''AS BLANK127,''AS BLANK128,''AS BLANK129,''AS BLANK130,''AS BLANK131,'' AS BLANK132
, C.SALETX_AMT, C.FREIGHT_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM AND D.WTHD_ENTITY = 'IRS'
LEFT OUTER JOIN PS_VCHR_LINE_WTHD DD ON DD.BUSINESS_UNIT = D.BUSINESS_UNIT AND DD.VOUCHER_ID = D.VOUCHER_ID AND DD.VOUCHER_LINE_NUM = D.VOUCHER_LINE_NUM AND DD.WTHD_ENTITY = 'PA'
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND C.ACCOUNTING_DT < '06-01-2021'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
AND C.MATCH_STATUS_VCHR = 'M'
AND C.APPR_STATUS = 'A'
AND B.VOUCHER_ID = '00720667' )
SELECT INVOICE_ID, VOUCHER_LINE_NUM - 1 + row_number() over (PARTITION BY INVOICE_ID, VOUCHER_LINE_NUM ORDER BY VOUCHER_LINE_NUM) AS VOUCHER_LINE_NUM,
LINE_TYPE, MERCHANDISE_AMT, INVOICE_QTY, UNIT_PRICE, UNIT_OF_MEASURE, DESCR , BLANK1, BLANK2--A.PO_ID, A.LINE_NBR,
, BLANK3, BLANK4,
BLANK5, BLANK6,BLANK7,BLANK777,BLANK8,BLANK9,BLANK10,BLANK11,BLANK12,
SEGMENTS, BLANK13, DATE1, BLANK14,BLANK15,BLANK16,BLANK17, BLANK18,
BLANK19,BLANK199,BLANK1999,BLANK20,BLANK21,BLANK211,BLANK22,BLANK23,BLANK24,BLANK25,BLANK26,BLANK27,BLANK28,
BLANK29,BLANK30,BLANK31,
BLANK133,
BLANK134, BLANK32, BLANK33, BLANK34,
BLANK35, BLANK36,
BLANK37, BLANK38,BLANK39,BLANK40,BLANK41,BLANK411,BLANK42, BLANK43, BLANK44,BLANK45,BLANK46,BLANK47,BLANK48,BLANK49,BLANK50,BLANK51,BLANK52,BLANK53,BLANK54,BLANK55,BLANK56,BLANK57,BLANK58,BLANK59,BLANK60,BLANK61,BLANK62,BLANK63,BLANK64,BLANK65,BLANK66,BLANK67,BLANK68,BLANK69,BLANK70,BLANK71,BLANK72,BLANK73,BLANK74,BLANK75,BLANK76,BLANK77,BLANK78,BLANK79,BLANK80,
BLANK81,BLANK82,BLANK83,BLANK84,BLANK85,BLANK86,BLANK87,BLANK88,BLANK89,BLANK90,BLANK91,BLANK92,BLANK93,BLANK94,BLANK95,BLANK96,BLANK97,BLANK98,BLANK99,BLANK100,BLANK101,BLANK102,BLANK103,BLANK104,BLANK105,BLANK106,BLANK107,BLANK108,BLANK109,BLANK110,BLANK111,BLANK112,BLANK113,BLANK114,BLANK115,BLANK116,BLANK117,BLANK118,BLANK119,BLANK120,BLANK121,BLANK122,BLANK123,BLANK124,BLANK125,BLANK126,BLANK127,BLANK128,BLANK129,BLANK130,BLANK131,BLANK132 , value
FROM CTE
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)) u
WHERE value > 0.00
You cannot include MERCHANDISE_AMT here:
unpivot (value FOR col IN (MERCHANDISE_AMT, FREIGHT_AMT, SALETX_AMT)
AND in your final SELECT from the UNPIVOT results (4th column result set).
Including it in the IN list here means that you are unpivoting the value of this column into your row structure, so you can no longer select its value in your final SELECT.
So you need to pick. Do you want to unpivot the values in MERCHANDISE_AMT? If so, then leave it in the IN list of your UNPIVOT and remove it from final SELECT. If not, then remove it from your IN list and leave it in your final SELECT.
Seems like you would likely benefit from reading through the Microsoft examples on UNPIVOT.

Wrap CTE inside another Select statement

Is it possible to wrap a CTE inside of another Select statement?
Here is my CTE:
WITH IRS AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'IRS' ) ,
PA AS
(SELECT BUSINESS_UNIT, VOUCHER_ID, VOUCHER_LINE_NUM, WTHD_ENTITY, WTHD_TYPE, WTHD_CLASS
FROM PS_VCHR_LINE_WTHD
WHERE WTHD_ENTITY = 'PA' )
SELECT IRS_WTHD.BUSINESS_UNIT, IRS_WTHD.VOUCHER_ID, IRS_WTHD.VOUCHER_LINE_NUM,
--COLUMN 1 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN 'PA'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'IRS'
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'IRS'
ELSE ''
END ,
--COLUMN 2 TO BE USED IN MAIN QUERY:
CASE WHEN PA_WTHD.WTHD_ENTITY = 'PA' THEN CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ','0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099N'
AND IRS_WTHD.WTHD_CLASS = '01' THEN 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
WHEN IRS_WTHD.WTHD_ENTITY = 'IRS'
AND IRS_WTHD.WTHD_TYPE = '1099'
AND IRS_WTHD.WTHD_CLASS = '07' THEN 'MISC7'
WHEN PA_WTHD.WTHD_ENTITY = '' THEN ''
ELSE 'MISC' + CAST(REPLACE(LTRIM(REPLACE(IRS_WTHD.WTHD_CLASS, '0', ' ')), ' ', '0') AS VARCHAR)
END
FROM IRS IRS_WTHD
LEFT JOIN PA PA_WTHD ON PA_WTHD.BUSINESS_UNIT = IRS_WTHD.BUSINESS_UNIT AND PA_WTHD.VOUCHER_ID = IRS_WTHD.VOUCHER_ID AND PA_WTHD.VOUCHER_LINE_NUM = IRS_WTHD.VOUCHER_LINE_NUM
I would like to wrap the above CTE inside of this main SQL Select statement below and output the two CASE statement columns above into the final SELECT statement below while joining on BUSINESS_UNIT, VOUCHER_ID, and VOUCHER_LINE_NUM fields from the PS_VCHR_LINE_WTHD table :
--Main Select Statement:
SELECT CONCAT(A.BUSINESS_UNIT,A.VOUCHER_ID) AS INVOICE_ID, A.VOUCHER_LINE_NUM,
CASE WHEN EXISTS (SELECT 1 FROM PS_DISTRIB_LINE
WHERE BUSINESS_UNIT = A.BUSINESS_UNIT
AND VOUCHER_ID = A.VOUCHER_ID
AND VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM)
THEN 'ITEM' ELSE 'MISCELLANEOUS' END, A.MERCHANDISE_AMT, B.QTY_VCHR, A.UNIT_PRICE, A.UNIT_OF_MEASURE, A.DESCR, A.PO_ID, A.LINE_NBR,
A.SCHED_NBR, B.PO_DIST_LINE_NUM, A.DESCR254_MIXED, '','',
F.OR_ENTITY + '.' + F.OR_LOCATION + '.' + CASE WHEN B.BUSINESS_UNIT_GL IN ('90000', '90032', '90059') AND H.DEPTID = '741' THEN H.COST_CENTER
WHEN B.BUSINESS_UNIT_GL = '90000' AND H.DEPTID = '956' THEN H.COST_CENTER
WHEN B.DEPTID IN ('882', '883', '884', '885', '886', '803' , '887', '888') THEN '676'
ELSE '000' END
+ '.' + B.ACCOUNT + '.' + ISNULL(G.ORACLE_PROJECT_CODE,'000000000.') + ISNULL(NULLIF(B.AFFILIATE, ''), '00000.') + '.000000.' + '000000' ,'', C.ACCOUNTING_DT, '',
'','','', ISNULL(D.WTHD_ENTITY,''), '', '', '', A.SALETX_AMT
FROM PS_VOUCHER_LINE A
LEFT OUTER JOIN PS_DISTRIB_LINE B ON B.BUSINESS_UNIT = A.BUSINESS_UNIT AND B.VOUCHER_ID = A.VOUCHER_ID AND B.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VOUCHER C ON C.BUSINESS_UNIT = A.BUSINESS_UNIT AND C.VOUCHER_ID = A.VOUCHER_ID
LEFT OUTER JOIN PS_VCHR_LINE_WTHD D ON D.BUSINESS_UNIT = A.BUSINESS_UNIT AND D.VOUCHER_ID = A.VOUCHER_ID AND D.VOUCHER_LINE_NUM = A.VOUCHER_LINE_NUM
LEFT OUTER JOIN PS_VENDOR E ON E.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND E.VENDOR_ID = A.VENDOR_ID
LEFT OUTER JOIN #CloudXWalk F ON F.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND (F.DEPTID = 'All' OR F.DEPTID = B.DEPTID)
LEFT OUTER JOIN #CloudCostCenter H ON H.BUSINESS_UNIT = B.BUSINESS_UNIT_GL AND H.DEPTID = B.DEPTID
LEFT OUTER JOIN #CloudProjectCodes G ON G.PS_PROJECT_CODE = B.PROJECT_ID
LEFT OUTER JOIN PS_PYMNT_VCHR_XREF I ON I.BUSINESS_UNIT = A.BUSINESS_UNIT AND I.VOUCHER_ID = A.VOUCHER_ID
WHERE C.INVOICE_DT > '01-03-2019'
AND I.PYMNT_ID = ''
AND C.CLOSE_STATUS <> 'C'
AND C.ENTRY_STATUS <> 'X'
ORDER BY 1,2
Is this possible, or is there an alternate way of avoiding using the CTE? I am using the CTE because I need to be able to run Case statements across multiple rows and possibly return data on other rows.

SQL Server 2008 Specified column was specified multiple times

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.

Error: "Multiple columns are specified in an aggregated expression containing an outer reference."

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!

How to change this 'Not In' Query to Left Join query

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