I have a table that i wanted to create some charts.
Basically i need to know how many registers i have in interval of 10 minutes and how many of them are already pos-processed. With this 2 queries i have the info i need, but i need they 2 in just 1 result table.
First query
SELECT
(
CAST(DATEPART(HOUR, m.Ocr_DataHora) AS NVARCHAR) +
':' +
CAST((DATEPART(MINUTE, m.Ocr_DataHora) % 6) AS NVARCHAR) +
'0'
) AS Hora,
COUNT(*) AS Movimentações
FROM
Integracao m
WHERE
m.Ocr_DataHora >= '2012-09-17 00:00:00.000'
AND m.Ocr_DataHora < '2012-09-18 00:00:00.000'
GROUP BY
DATEPART(HOUR, m.Ocr_DataHora),
(DATEPART(MINUTE, m.Ocr_DataHora) % 6)
ORDER BY
DATEPART(HOUR, m.Ocr_DataHora),
(DATEPART(MINUTE, m.Ocr_DataHora) % 6)
Second query
SELECT
(
CAST(DATEPART(HOUR, s.Ocr_DataHora) AS NVARCHAR) +
':' +
CAST((DATEPART(MINUTE, s.Ocr_DataHora) % 6) AS NVARCHAR) +
'0'
) AS Hora,
COUNT(*) AS Sucesso
FROM
Integracao s
WHERE
s.Veiculo_Modelo <> ''
AND s.Ocr_DataHora >= '2012-09-17 00:00:00.000'
AND s.Ocr_DataHora < '2012-09-18 00:00:00.000'
GROUP BY
DATEPART(HOUR, s.Ocr_DataHora),
(DATEPART(MINUTE, s.Ocr_DataHora) % 6)
How can i join them if my common field is generated dynamically?
As others have already told you, you could just use the two queries as derived tables (subselects) and join them using each one’s
Horacolumn. It doesn’t matter if the column is computed in the query, it’s perfectly legal to use it in a join condition.However, I think you can get the same results more efficiently, by calculating both counts in a single query (i.e. without subqueries). Here’s how you can do that:
As you can see, the query doesn’t filter rows on
s.Veiculo_Modelo <> ''. However, that condition is used when counting rows for theSucessocolumn. The argument of the secondCOUNTis a CASE expression. It returns a value (arbitrarily chosen to be1, but could be anything really) if the specified condition is met andNULLotherwise. SinceCOUNTomits nulls, the result will be the same as with your dedicated query calculating and returningSucesso.