SQL Show dates without transactions as value = 0 - sql

I'm doing a weight reporting and I have a problem. I use this query to know the enters of weight in our warehouse, but when there are no transactions in a date this date doesn't appears in the results.
SELECT erp.MKPF.BUDAT AS Data,
Sum( erp.MSEG.MENGE * erp.MARM.BRGEW ) as pes
From erp.MKPF
INNER Join erp.MSEG on erp.MKPF.MANDT = erp.MSEG.MANDT and erp.MKPF.MBLNR = erp.MSEG.MBLNR
INNER Join erp.MARM on erp.MSEG.MANDT = erp.MARM.MANDT and erp.MSEG.MATNR = erp.MARM.MATNR And erp.MSEG.MEINS = erp.MARM.MEINH
INNER JOIN erp.MARA on erp.MSEG.MANDT = erp.MARA.MANDT and erp.MSEG.MATNR = erp.MARA.MATNR
WHERE erp.MKPF.MANDT = '100'
and erp.MKPF.BUDAT >= '20120720'
and erp.MKPF.BUDAT <= CONVERT(VARCHAR(8), GETDATE(), 112) -1
and erp.MSEG.LGORT in ('1001','1069')
and erp.MSEG.BWART In ('101','102','311','312')
and erp.MSEG.WERKS = '1001'
and erp.MARA.MTART in ('Z001','Z010','Z002','Z02E')
GROUP BY erp.MKPF.BUDAT*
Now the results are like this:
Data PES
20120720 9999999.9999
20120721 9999999.8888
20120723 9999999.7777
And i need this
Data PES
20120720 9999999.9999
20120721 9999999.8888
20120722 0
20120723 999999.7777
Can somebody help me?

Use a table or a view to generate the date range of interest and let this drive the query. Then you outer join your results to this view. This can be done dynamically in the query. For example, in Oracle, you can use "connect by" to generate a series:
create table my_summary(the_day date, pes number);
insert into my_summary values(to_date('20120720', 'yyyymmdd'), 9999999.9999);
insert into my_summary values(to_date('20120721', 'yyyymmdd'), 9999999.8888);
insert into my_summary values(to_date('20120723', 'yyyymmdd'), 9999999.7777);
SELECT d.the_day, NVL(s.pes, 0) AS pes
FROM ( SELECT to_date('20120720', 'yyyymmdd') + level -1 AS the_day
FROM dual CONNECT BY level <= 4) d
LEFT OUTER JOIN my_summary s ON (d.the_day = s.the_day)
ORDER BY 1
THE_DAY PES
--------- ---
20-JUL-12 9999999.9999
21-JUL-12 9999999.8888
22-JUL-12 0
23-JUL-12 9999999.7777
Other rdbms have other methods to generate a series. This will require you to know the start date you want, and the number of records (in the example above 20120720 and 4).

Thanks to all, finally I did this and it works
SELECT
c.BUDAT AS DATA,
CASE When SAP.pes Is Null then '0'
ELSE SAP.pes
END
From
erp.YSD_CALENDAR as c LEFT JOIN
(SELECT
erp.MKPF.BUDAT,
Sum(
erp.MSEG.MENGE
* erp.MARM.BRGEW ) as pes
FROM
erp.MKPF
INNER Join erp.MSEG on erp.MKPF.MANDT = erp.MSEG.MANDT and erp.MKPF.MBLNR = erp.MSEG.MBLNR
INNER Join erp.MARM on erp.MSEG.MANDT = erp.MARM.MANDT and erp.MSEG.MATNR = erp.MARM.MATNR And erp.MSEG.MEINS = erp.MARM.MEINH
INNER JOIN erp.MARA on erp.MSEG.MANDT = erp.MARA.MANDT and erp.MSEG.MATNR = erp.MARA.MATNR
WHERE
erp.MKPF.MANDT = '100'
and erp.MKPF.BUDAT >= '20120720'
and erp.MSEG.LGORT in ('1001','1069')
and erp.MSEG.BWART In ('101','102','311','312')
and erp.MSEG.WERKS = '1001'
and erp.MARA.MTART in ('Z001','Z010','Z002','Z02E')
and erp.MSEG.SHKZG = 'S'
GROUP BY erp.MKPF.BUDAT
) SAP ON SAP.BUDAT = c.BUDAT
WHERE
c.BUDAT >= '20120720'
and c.BUDAT <= CONVERT(VARCHAR(8), GETDATE(), 112)
GROUP BY c.BUDAT, SAP.pes
ORDER BY c.BUDAT

Related

Why is SQL doing an inner join where an outer join is needed

I have two tables which I want to "outer" join (and then fetch) using SQL. The exact SQL query (in question) is:
SELECT
LEFT(a.cusip, 6) AS cusip6,
a.date, a.prc, a.ret, a.vol, a.spread, a.shrout,
b.epsf12, (b.seqq-b.pstkq) / b.cshoq AS bps
FROM
crsp.msf a
FULL JOIN
compa.fundq b ON (LEFT(a.cusip, 6) = LEFT(b.cusip, 6)
AND a.date = b.datadate)
WHERE
(b.datadate BETWEEN '2010-01-01' and '2015-12-31')
AND (a.date BETWEEN '2010-01-01' and '2015-12-31')
AND (b.cshoq > 0)
This returns 670'293 rows.
But when I fetch the two datasets separately and (outer) join them through R-merge(), I get 1'182'093 rows. The two separate queries I use are:
SELECT
LEFT(cusip, 6) AS cusip6, date, prc, ret, vol, spread, shrout
FROM
crsp.msf
WHERE
date BETWEEN '2010-01-01' and '2015-12-31'
SELECT
LEFT(cusip, 6) AS cusip6, datadate AS date, epsf12,
(seqq-pstkq)/cshoq AS bps
FROM
compa.fundq
WHERE
datadate BETWEEN '2010-01-01' and '2015-12-31'
AND cshoq > 0
And then I merge (outer join) using:
merge(x = data_1, y = data_2, by.x = c("cusip6", "date"), by.y = c("cusip6", "date"), all = T)
This returns 1'182'093 rows which is correct. So my original (first) SQL query is in fact performing an "inner join" when I explicitly specify an outer join. The below R-merge() returned 670'293 rows re-validating that the fetched data from SQL is indeed an inner join.
merge(x = data_1, y = data_2, by.x = c("cusip6", "date"), by.y = c("cusip6", "date"))
What am I doing wrong with my SQL query?
Because the WHERE clause is applied after the JOINs. At this point there are NULL values (as a result of 'failed' JOINs), and those rows fail the WHERE clause.
If you want an OUTER JOIN and a filter, put the filter in the JOIN or a sub-query.
SELECT
LEFT(a.cusip, 6) AS cusip6,
a.date, a.prc, a.ret, a.vol, a.spread, a.shrout,
b.epsf12, (b.seqq-b.pstkq) / b.cshoq AS bps
FROM
(SELECT * FROM crsp.msf WHERE date BETWEEN '2010-01-01' and '2015-12-31') a
FULL JOIN
(SELECT * FROM compa.fundq WHERE datadate BETWEEN '2010-01-01' and '2015-12-31' AND cshoq > 0) b
ON LEFT(a.cusip, 6) = LEFT(b.cusip, 6)
AND a.date = b.datadate

create an classification for months ordered

I'm trying to create an column in my query to show an ordered classification ( show 1, 2, 3 ( as in first, second, third ...)) relative to date... in my current query i have filtered data from the last 12 months ( as example, from 1-9-2016 to 31-8-2017)
using DATEADD(mm; DATEDIFF(m; - 1; GETDATE()) - 12; 0)
for the first date and
DATEADD(s; - 1; DATEADD(mm; DATEDIFF(m; 0; GETDATE()) + 1; 0))
for the last day of the current month. And i also have two columns, one with the month and other with the year, both extracted from a document date column present in the data ( i'm using
MONTH(dbo.Mov_Venda_Cab.dtmData) and YEAR(dbo.Mov_Venda_Cab.dtmData)).
My goal is to have a column showing something like this :
If the month is the first from the interval ( if is month 9 and year 2016 ) is has to show 1 , if is the second ( month 10 and year 2016) , show 2, all continuously until the current month ( that is 8 and year 2017) and showing 12.
If the values where static i could do a simple case and would achieve what i wanted. My problem is that since when i get the data filtered by my current date and the 12 months behind, i don't manage to get the same result because i don't know exactly what i should do in the CASE expression.
so that it could help my columns are :
Item ; Qty ; Month ; Year ; dtmData ; orderedMonth
ORIGINAL QUERY :
SELECT DISTINCT DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0) AS DATA_INI,
DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) AS DATA_FIM,
dbo.Mov_Venda_Lin.Id,
MONTH(dbo.Mov_Venda_Cab.dtmData) AS Mes,
YEAR(dbo.Mov_Venda_Cab.dtmData) AS Ano,
dbo.Mov_Venda_Lin.fltValorMercadoriaSIVA * dbo.Mov_Venda_Cab.intSinal AS Mercadoria,
dbo.Mov_Venda_Lin.fltValorLiquido * dbo.Mov_Venda_Cab.intSinal AS ValorLiquido,
CASE
WHEN tbl_tipos_documentos.bitconsideraqtdmapas = 1
THEN (Mov_Venda_Lin.fltQuantidade * mov_venda_cab.intsinal)
ELSE 0
END AS Quantidade,
dbo.Mov_Venda_Lin.strCodSeccao AS Seccao,
dbo.Mov_Venda_Lin.strAbrevTpDoc AS TpDoc,
dbo.Tbl_Tipos_Documentos.strDescricao AS DescTpDoc,
dbo.Mov_Venda_Lin.intNumLinha AS Linha,
dbo.Mov_Venda_Lin.strCodExercicio AS Exercicio,
dbo.Mov_Venda_Cab.strAbrevMoeda AS Moeda,
dbo.Mov_Venda_Cab.fltCambio AS Cambio,
dbo.Mov_Venda_Lin.strCodArtigo AS Artigo,
dbo.Tbl_Gce_Artigos.strDescricao AS DescArtigo,
dbo.Mov_Venda_Lin.strCodClassMovStk AS MovStk,
dbo.Tbl_ClassificacaoMovStk.strDescricao AS DescMovStk,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strcodigo
ELSE NULL
END AS TpEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strdescricao
ELSE NULL
END AS DescTpEntidade,
CASE
WHEN mov_venda_cab.intcodentidade <> 0
THEN mov_venda_cab.intcodentidade
ELSE NULL
END AS CodEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
AND mov_venda_cab.intcodentidade <> 0
THEN 'Cliente'
WHEN mov_venda_cab.inttpentidade = 1
AND mov_venda_cab.intcodentidade <> 0
THEN 'Outro Devedor'
ELSE NULL
END AS TipoEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_clientes.strnome
ELSE tbl_outros_devedores.strnome
END AS DescNome,
dbo.Tbl_SubZonas.strAbrevZona AS Zona,
dbo.Tbl_Zonas.strDescricao AS DescZona,
dbo.Mov_Venda_Cab.strAbrevSubZona AS SubZona,
dbo.Tbl_SubZonas.strDescricao AS DescSubZona,
dbo.Mov_Venda_Cab.intCodVendedor AS Vendedor,
dbo.Tbl_Gce_Vendedores.strNome AS DescNomeVend,
dbo.Tbl_Gce_Artigos.strCodCategoria AS Categoria,
dbo.Tbl_Gce_Categorias.strDescricao AS DescCategoria,
dbo.Tbl_Gce_Artigos.strTpArtigo AS TpArtigo,
dbo.Tbl_Gce_Tipos_Artigos.strDescricao AS DescTpArtigo,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaAgrup,
CAST(NULL AS VARCHAR(35)) AS DescFamAgrup,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaRes,
CAST(NULL AS VARCHAR(35)) AS DescFamRes,
dbo.Mov_Venda_Cab.strForteAbrevMoeda AS abrevmoeda,
dbo.Mov_Venda_Cab.fltForteCambio AS fortecambio
FROM dbo.Mov_Venda_Lin WITH (NOLOCK)
LEFT OUTER JOIN dbo.Mov_Venda_Cab WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodSeccao = dbo.Mov_Venda_Cab.strCodSeccao
AND dbo.Mov_Venda_Lin.strAbrevTpDoc = dbo.Mov_Venda_Cab.strAbrevTpDoc
AND dbo.Mov_Venda_Lin.strCodExercicio = dbo.Mov_Venda_Cab.strCodExercicio
AND dbo.Mov_Venda_Lin.intNumero = dbo.Mov_Venda_Cab.intNumero
LEFT OUTER JOIN dbo.Tbl_Gce_Armazens WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodArmazem = dbo.Tbl_Gce_Armazens.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Mov_Venda_Lin.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosFamilias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosFamilias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Familias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosFamilias.strCodFamilia = dbo.Tbl_Gce_Familias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosReferencias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosReferencias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Referencias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosReferencias.strCodReferencia = dbo.Tbl_Gce_Referencias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strTpArtigo = dbo.Tbl_Gce_Tipos_Artigos.strCodigo
LEFT OUTER JOIN dbo.Tbl_Clientes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Clientes.intCodigo
LEFT OUTER JOIN dbo.Tbl_Direccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Direccoes.intCodigo
AND dbo.Mov_Venda_Cab.intDireccao = dbo.Tbl_Direccoes.intNumero
AND dbo.Mov_Venda_Cab.intTpEntidade = dbo.Tbl_Direccoes.intTp_Entidade
LEFT OUTER JOIN dbo.Tbl_Outros_Devedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Outros_Devedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Vendedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodVendedor = dbo.Tbl_Gce_Vendedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Tipos_Documentos WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevTpDoc = dbo.Tbl_Tipos_Documentos.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_SubZonas WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevSubZona = dbo.Tbl_SubZonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Zonas WITH (NOLOCK)
ON dbo.Tbl_SubZonas.strAbrevZona = dbo.Tbl_Zonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Gce_Categorias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodCategoria = dbo.Tbl_Gce_Categorias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Seccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strCodSeccao = dbo.Tbl_Gce_Seccoes.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Entidade WITH (NOLOCK)
ON dbo.Tbl_Clientes.strTpEntidade = dbo.Tbl_Gce_Tipos_Entidade.strCodigo
LEFT OUTER JOIN dbo.Tbl_ClassificacaoMovStk WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodClassMovStk = dbo.Tbl_ClassificacaoMovStk.strCodigo
WHERE (dbo.Mov_Venda_Cab.intTpEntidade = 0
OR dbo.Mov_Venda_Cab.intTpEntidade IS NULL)
AND (dbo.Mov_Venda_Cab.strAbrevTpDoc IN ('CRFCX', 'FACIV', 'FACTC', 'FCTA', 'LANIV', 'LOFX', 'LONC', 'LXANI', 'NCFCX', 'NFACC', 'NFACE', 'NFACM', 'NFACT', 'NNCRC', 'NNCRE', 'NNCRM', 'NNDEB', 'NNDEC', 'NNDEV', 'NVDIC', 'NVDIN', 'XLACC', 'XLACD'))
AND (dbo.Mov_Venda_Cab.strCodSeccao IN ('1', 'ENCT1', 'ENCT2', 'ENCT3', 'ENCT4', 'ENCT5', 'ENCT6'))
AND (dbo.Mov_Venda_Cab.dtmData > DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0))
AND (dbo.Mov_Venda_Cab.dtmData <= DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)))
AND (dbo.Mov_Venda_Lin.intTpLinha > 2)
AND (dbo.Mov_Venda_Cab.bitAnulado = 0)
AND (dbo.Mov_Venda_Cab.bitConvertido = 0)
Luckily there's a much less complicated method than using a bunch of CASE statements. You can use the ROW_NUMBER function.
First, don't split your dates into month and year. Just use Getdate() to calculate your desired range and compare your source dates to that. Then you add the ROW_NUMBER to get your ordering output:
SELECT
*
,ordered_output = (ROW_NUMBER()OVER(PARTITION BY grouping_field ORDER BY cast(dtmData as datetime) ASC))
FROM Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
This example assumes your have some ID field or similar on which your want to group your output, represented by grouping_field in the example. Your results would look like:
grouping_field dtmData ordered_output
1 8/1/2017 1
1 8/2/2017 2
1 8/3/2017 3
2 8/1/2017 1
2 8/2/2017 2
2 8/3/2017 3
If you don't want to group your output, just ordering everything by the date, you can omit the PARTITION BY grouping_field text. You'd get instead something like:
dtmData ordered_output
8/1/2017 1
8/2/2017 2
8/3/2017 3
8/4/2017 4
8/5/2017 5
8/6/2017 6
EDIT: Asker clarified that all records with the same month should get the same ordered output.
To do that you first need to assign each month/year combo a rank and rejoin that to the main table using two layers of subqueries:
SELECT b.*, c.month_rank
from Mov_Venda_Cab as b
inner join
(select mnt, yr, ROW_NUMBER() OVER(ORDER BY A.yr, A.mnt) AS month_rank
from (
SELECT DISTINCT
MONTH(dtmData) as mnt
, YEAR(dtmData) as yr
from Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
) as a
) as c
on MONTH(b.dtmData) = c.mnt and YEAR(b.dtmData) = c.yr

SQL query with pivot gives error

I have the following SQL query:
SELECT *
FROM (
SELECT ClientNumber, ClientName, YearEndDate, schedule, a1, ad1, a2, ad2, a3, ad3,
cv.[id] as CvId,
[dataCV] =
CASE cv.[id]
WHEN 'DATUM_AVA' THEN CONVERT(DATETIME, cv.[data], 112)
WHEN 'RECHTSVORM' THEN cv.[data]
END,
DATEADD(day, 30, [data]) AS Stat_Filing_Date,
To_Be_Filed =
CASE
WHEN DATEADD(day, 30, [data]) < GETDATE() THEN 'Yes'
ELSE 'No'
END
FROM EngagementFiles ef
INNER JOIN ac
ON ef.id = ac.EngagementFile_Id
INNER JOIN cv
ON ef.id = cv.EngagementFile_Id
RIGHT JOIN sh
ON ac.short_name = sh.a3 OR ac.short_name = sh.a2 OR ac.short_name = sh.a1
WHERE (schedule = 'G21-9A' OR schedule = 'G21-9B') AND sh.EngagementFile_Id = ef.id AND (ac.act_type = 'C' OR ac.act_type = 'H')
AND schedule =
CASE WHEN
(
SELECT cv.[data]
FROM cv
WHERE [id] = 'REPORT_TYPE' AND cv.EngagementFile_Id = ef.id
) LIKE '%VKT%' THEN 'G21-9B' ELSE 'G21-9A' END
AND ((cv.[id] = 'DATUM_AVA' AND cv.[form] = '' AND cv.[group] = ''))
) AS s
PIVOT (
MAX(dataCV)
FOR [CvId] IN ([DATUM_AVA]
)
)AS pvt
This returns the following result:
Now I want to add another column in the pivot part which also comes from the cv table. The structure of this table is kind of weird. It has the following columns:id, form, group and data.
The columns id, form and group are actually some kind of unique id which is used in a different application.
The column i want to add contains the data from the cv table where id = RECHTSVORM and group and form are empty.
The query with which I tried this is the following:
SELECT *
FROM (
SELECT ClientNumber, ClientName, YearEndDate, schedule, a1, ad1, a2, ad2, a3, ad3,
cv.[id] as CvId,
[dataCV] =
CASE cv.[id]
WHEN 'DATUM_AVA' THEN CONVERT(DATETIME, cv.[data], 112)
WHEN 'RECHTSVORM' THEN cv.[data]
END,
DATEADD(day, 30, [data]) AS Stat_Filing_Date,
To_Be_Filed =
CASE
WHEN DATEADD(day, 30, [data]) < GETDATE() THEN 'Yes'
ELSE 'No'
END
FROM EngagementFiles ef
INNER JOIN ac
ON ef.id = ac.EngagementFile_Id
INNER JOIN cv
ON ef.id = cv.EngagementFile_Id
RIGHT JOIN sh
ON ac.short_name = sh.a3 OR ac.short_name = sh.a2 OR ac.short_name = sh.a1
WHERE (schedule = 'G21-9A' OR schedule = 'G21-9B') AND sh.EngagementFile_Id = ef.id AND (ac.act_type = 'C' OR ac.act_type = 'H')
AND schedule =
CASE WHEN
(
SELECT cv.[data]
FROM cv
WHERE [id] = 'REPORT_TYPE' AND cv.EngagementFile_Id = ef.id
) LIKE '%VKT%' THEN 'G21-9B' ELSE 'G21-9A' END
AND ((cv.[id] = 'DATUM_AVA' AND cv.[form] = '' AND cv.[group] = '')
OR (cv.[id] = 'RECHTSVORM' AND cv.[form] = '' AND cv.[group] = ''))
) AS s
PIVOT (
MAX(dataCV)
FOR [CvId] IN ([DATUM_AVA],
[RECHTSVORM]
)
)AS pvt
But this gives the following error:
Conversion failed when converting date and/or time from character
string.
I'm guessing this is because for the RECHTSVORM column it is also trying to convert cv.data to a datetime.
What do I need to change in order for the query to only convert cv.data to datetime for the DATUM_AVA column?
It's possible that one of the Data values in the 'DATUM_AVA' rows is not in the correct format for a 112 style DATETIME. In this case 'yyyymmdd'. See CAST and CONVERT in the MSDN. You can check by selecting from the cv table with the same predicates and checking the values.
Irrespective of the above the column you are creating, dataCV, cannot be more than one data type. You are potentially trying to insert a DATETIME value and values with the originating column data type in to the created dataCV column. If you need to know that it is a DATETIME value, add an additional column to the pivot to help you identify the potential data type. You can then convert afterwards.

Subquery returned more than 1 value. My WHERE clause needs to remove SELECT statements

I have a SQL Stored Procedure that is giving issues. I am aware that it is most likely the SELECT statements in the WHERE clause that are returning multiple values. I commented out the WHERE and results were returned.
My question is how do I modify the statement so that I can still filter on those conditions?
Stored Proc code:
SELECT
REPORT_SPOOL.ID,
REPORT_SPOOL.REPORT_SPOOL_TYPE_ID,
REPORT_SPOOL.FUND_ID,
REPORT_SPOOL.PERF_ENTITY_ID,
REPORT_SPOOL.REPORT_GUID,
REPORT_SPOOL.REPORT_TEMPLATE_GUID,
PERF_ENTITY.CODE AS PERF_ENTITY_CODE,
PERF_ENTITY.NAME AS PERF_ENTITY_NAME,
FUND.CODE AS FUND_CODE,
FUND.NAME AS FUND_NAME,
REPORT.CODE AS REPORT_CODE,
REPORT.NAME AS REPORT_NAME,
REPORT_TEMPLATE.CODE AS REPORT_TEMPLATE_CODE,
REPORT_TEMPLATE.NAME AS REPORT_TEMPLATE_NAME,
FUND.ACCOUNTING_START AS START_DATE,
FUND.ACCOUNTING_END AS END_DATE
FROM
PERF_ENTITY
RIGHT OUTER JOIN
REPORT
INNER JOIN
REPORT_SPOOL
ON REPORT.GUID = REPORT_SPOOL.REPORT_GUID
INNER JOIN
REPORT_TEMPLATE
ON REPORT_SPOOL.REPORT_TEMPLATE_GUID = REPORT_TEMPLATE.GUID
ON PERF_ENTITY.ID = REPORT_SPOOL.PERF_ENTITY_ID
LEFT OUTER JOIN
FUND
ON REPORT_SPOOL.FUND_ID = FUND.ID
WHERE
(END_DATE IS NULL OR END_DATE > #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID = (SELECT FUND_ID FROM FUND_HLD WHERE [DATE] = #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID = (SELECT FUND_ID FROM FUND_TRD_LINE_VIEW WHERE [DATE] >= (SELECT DATEFROMPARTS(YEAR(#REPORT_DATE),MONTH(#REPORT_DATE),1)) AND [DATE] <= #REPORT_DATE)
Those last 2 SELECTS are the issue
Replace = with in in the sub query:
REPORT_SPOOL.FUND_ID in (SELECT FUND_ID FROM FUND_HLD WHERE [DATE] = #REPORT_DATE)
AND
REPORT_SPOOL.FUND_ID in (SELECT FUND_ID FROM FUND_TRD_LINE_VIEW WHERE [DATE] >= (SELECT DATEFROMPARTS(YEAR(#REPORT_DATE),MONTH(#REPORT_DATE),1)) AND [DATE] <= #REPORT_DATE)

How work with subquery in a View?

I need create a View for this Query, allowing change m.arq_data and m2.arq_data values when a select uses this View, like:
select * FROM the_view WHERE m.arq_data = X AND m2.arq_data = Y
Here is my current query:
SELECT distinct(p.num_processo),p.num_proc_jud,a.assunto,su.subassunto,ma.Materia,u.Unidade ,M.COD_UNIDADE as cod_serv ,u.Unidade as servidor ,' ' as serv_ativo,
' ' as data_vinc ,' ' as V_ativo, M.motivo,M.data_movimentacao as data_mov_distr ,
(select max(m2.arq_data) from movimentacao m2 where m2.arq_data
BETWEEN '2011-08-01 00:00:00'AND '2011-08-31 23:00:00' and m2.num_processo =
p.num_processo) as Data_Arq_Desarq , status = 'A'
--pra view
, M.arq_data
FROM processo p
INNER JOIN assunto a ON a.cod_assunto = p.cod_assunto
INNER JOIN subassunto su ON su.cod_subassunto = p.cod_subassunto
LEFT JOIN materia ma ON ma.cod_materia = p.cod_materia
inner JOIN movimentacao M on M.num_processo = p.num_processo
INNER JOIN Unidade u ON u.cod_unidade = M.COD_UNIDADE
where
not exists(select * from anexos a where a.num_proc_anexo = p.num_processo and a.ativo = 1)
and not exists(select * from movimentacao m1 where m1.num_movimentacao= M.num_movimentacao and m1.motivo = 10 and m1.arquivado = 0)
and ( not exists (select * from distrib_vincjud d2 where d2.num_processo = p.num_processo)
or p.num_processo in (select d3.num_processo from distrib_vincjud d3
where d3.num_processo = p.num_processo
and d3.cod_servidor not in(select cod_servidor from servidor)
and d3.id_vinc in (select max(d4.id_vinc) from distrib_vincjud d4
where d4.num_processo = d3.num_processo and d4.data_vinc <= M.arq_data )))
and M.COD_UNIDADE in (select M.COD_UNIDADE from movimentacao m2 where
(m2.cod_ORIGEM_MOV = '26000181' or m2.cod_ORIGEM_MOV = '2600000X')and m2.num_processo = p.num_processo)
and p.tipo = 'J'
and M.arq_data >= '2011-08-01 00:00:00'AND M.arq_data <='2011-08-31 23:00:00'
View cannot take parameters. Implement it as table-valued udf instead (or stored procedure).
If you are saying you want to define your view to work with changing dates for conditions like m2.arq_data BETWEEN '2011-08-01 00:00:00'AND '2011-08-31 23:00:00' then it depends what your requirements are.
For instance if this date range will always be between today and 31 days from now then you could change this line to be something like this:
m2.arq_data BETWEEN GetDate() AND DATEADD (dd, 31, GetDate())
If the date range is not something fairly simple that can be defined generically using SQL then you might want to consider using a stored proc or a udf and passing it the date params.