I have multiple calculations that use union and i am trying to combine them so i can load them into a new table on the same row.
Below is an example of the calculations, i will have 8 in total. I want to load the results to a new summary table via a stored proc but I am not sure on how to proceed in terms of combining/loading these calcs.
The summary table will contain 8 calc columns, and the name column and a load date. It will only ever contain 1 row as the data is deleted and reloaded throughout the day.
--current day
select Name, count(cast (id as int)) as current_day from (
select Name,id from [Table1]
where CONVERT(DATE, dte_Uploaded) = CONVERT(DATE, CURRENT_TIMESTAMP)
union all
select Name,id from from [Table2]
where CONVERT(DATE, dte_Uploaded) = CONVERT(DATE, CURRENT_TIMESTAMP)
) x group by Name
--current week
select Name, count(cast (id as int)) as current week from (
select Name,id from [Table1]
where DATEDIFF(ww, dte_Uploaded, GETDATE()) = 0
union all
select Name,id from from [Table2]
where DATEDIFF(ww, dte_Uploaded, GETDATE()) = 0
) x group by Name
--current month
select Name, count(cast (id as int)) as current_month from (
select Name,id from [Table1]
where DATEDIFF(m, dte_Uploaded, GETDATE()) = 0
union all
select Name,id from from [Table2]
where DATEDIFF(m, dte_Uploaded, GETDATE()) = 0
) x group by Name
2条答案
按热度按时间7cwmlq891#
If target table contains only one row, I presume that each of queries you posted also contains only one row. Because, if they don't, how will you know which row to pick?
Anyway: one option is to use your current queries as CTEs (common table expressions; a new way to use subqueries), cross join them and fetch columns you're interested in.
For example:
If cross join won't work, then you should know how to properly join results returned by each CTE.
Finally, how to insert values into the target table? Like this:
mrphzbgm2#
You might have better performance and improved readability if you calculate proper date ranges in advance and use conditional aggregation to calculate your counts.
When calculating date ranges, it is common to calculate an inclusive start date and an exclusive end date (00:00:00 at the start of the day afterwards). This nicely handles date/time fields without having to truncate potentially indexed column values.
Conditional aggregation combines an aggregate function (in this case
COUNT()
) with aCASE
expression that either includes or excludes each value from the aggregation. ForCOUNT()
theTHEN 1
rows are counted, while the implicitELSE NULL
rows are not.Try something like:
If dte_Uploaded is indexed, the above will efficiently retrieve only those rows needed for the current calculation, rather than a less-efficient table scan.
If you are using older versions of SQL server that do not support the
DATETRUNC()
,LEAST()
, andGREATEST()
functions, the following alternate date calculations can be used:Depending how your site defines the start of a week, the week ranges might need to be tweaked.