SQL Server手动将记录记录添加到视图

时间:2012-02-14 13:23:35

标签: sql sql-server view reporting-services ssrs-2008

我的视图包含下图中显示的数据。 该视图显示,本财政年度每个月有多少工作日可用于取消学校/银行假期。

由于8月份的零日可用,因此本月将其排除在外。

由于8月份可用的总天数总是为零,因此将SQL硬编码为8月份总数为0,以及4月至8月的记录与4月份相同似乎是可以接受的。七月。

添加这两条记录的最佳方式是什么,以及代码应放在哪里,请参阅代码布局示例:

请参阅链接(已回答问题)代码布局:

  

SQL populate total working days per month minus bank holidays for current financial year

enter image description here

2 个答案:

答案 0 :(得分:0)

对于我的回答,我假设您的视图vDays的列与您的屏幕截图相符:periodavailabledaysyear

要将任何零日期间附加到您的结果中,无论月份可能为零(这将适应8月和任何其他恰好零日的月份),您可以像这样扩展您的观点:

WITH Mths (Mth) AS (
    SELECT 'January'
    UNION SELECT 'February'
    UNION SELECT 'March'
    UNION SELECT 'April'
    UNION SELECT 'May'
    UNION SELECT 'June'
    UNION SELECT 'July'
    UNION SELECT 'August'
    UNION SELECT 'September'
    UNION SELECT 'October'
    UNION SELECT 'November'
    UNION SELECT 'December'
    UNION SELECT 'April - January'
    UNION SELECT 'April - February'
    UNION SELECT 'April - March'
    UNION SELECT 'April - May'
    UNION SELECT 'April - June'
    UNION SELECT 'April - July'
    UNION SELECT 'April - August'
    UNION SELECT 'April - September'
    UNION SELECT 'April - October'
    UNION SELECT 'April - November'
    UNION SELECT 'April - December'

), Years (Year) AS (
    SELECT DISTINCT year
    FROM   vDays

), ZeroPeriods (Mth, Years) AS (
    SELECT Mth, Year
    FROM   Mths, Years

), JoinedData (Mth, AvailableDays, Year) AS (
    SELECT Mth, 0, Years
    FROM   ZeroPeriods
    UNION ALL
    SELECT period, availabledays, year
    FROM   vDays

), GroupedData (Mth, AvailableDays, Year) AS (
    SELECT Mth, SUM(AvailableDays), Year
    FROM JoinedData
    GROUP BY Mth, Year

)
SELECT * 
FROM   GroupedData
ORDER BY Year, CASE UPPER(LEFT(Mth, 3)) 
               WHEN 'JAN' THEN 1 WHEN 'FEB' THEN 2 WHEN 'MAR' THEN 3
               WHEN 'APR' THEN 4 WHEN 'MAY' THEN 5 WHEN 'JUN' THEN 6
               WHEN 'JUL' THEN 7 WHEN 'AUG' THEN 8 WHEN 'SEP' THEN 9
               WHEN 'OCT' THEN 10 WHEN 'NOV' THEN 11 ELSE 12 END;

我已经把它拆分成许多单独的查询,虽然有些可以合并到子查询中,但这样做可以让它更清楚地理解。

答案 1 :(得分:0)

这会为您提供所需的结果集吗?

SELECT Period, DaysAvailable, Year FROM YOURVIEW
UNION ALL
SELECT DISTINCT 'April-August', DaysAvailable,  Year FROM YOURVIEW where Period = 'April-July'
UNION ALL
SELECT DISTINCT 'August', 0, YEAR FROM YOURVIEW