1

事情是这样的:我有一个表 DailyContent (dailyContentId, userId, weekDayId, eventId),我在其中存储某些天的项目(对于每个用户)。天分为不同的事件(每天更多的事件)。我想做的是选择项目(对于一个事件),但要选择不同的天数。天的 ID 从 1 到 7。如果“选择”天,我得到 dayId,否则我得到 null 作为输入参数。

如果选择多于一天,则仅返回所有天共有的项目。

如果没有选择日期,则不返回任何内容

我已经尝试过这样的事情,但我只得到了一天的结果。如果我选择超过一天,则返回 NOTHING(应返回为该事件存储两天的项目,如上所述)。

DECLARE @daysCount int -- only for incitation how many days are actually set
SET @daysCount = 0
IF (@mon IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@tue IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@wed IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@thu IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@fri IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@sat IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END
IF (@sun IS NOT NULL)
    BEGIN
        SET @daysCount = @daysCount+1
    END

-- Insert statements for procedure here
SELECT 
    DailyContent.dailyContentId

            FROM DailyContent

    WHERE
    eventId=@eventId AND (weekDayId=@mon OR
            weekDayId=@tue OR
            weekDayId=@wed  OR
            weekDayId=@thu  OR
            weekDayId=@fri  OR
            weekDayId=@sat  OR
            weekDayId=@sun)
    GROUP BY DailyContent.dailyContentId
    HAVING (COUNT(dailyContentId) = @daysCount)

这个 HAVING COUNT 有问题。如果我删除它,它可以正常工作,但前提是选择了一天。

实际上,我想要“如果参数为空则全选”的反面。

我正在使用 MS SQL 服务器 2008。

任何帮助将不胜感激。

4

2 回答 2

0

您是否尝试过使用额外的if condition方法来处理“未选择任何一天”的情况,例如:

IF (@daysCount<>0)
SELECT DailyContent.dailyContentId, DailyContent.itemId, title, defaultSmallImagePath
    FROM DailyContent
    LEFT OUTER JOIN
        itemsTranslations ON itemsTranslations.itemId = DailyContent.itemId
    LEFT OUTER JOIN
        itemAdditionalInformation ON itemAdditionalInformation.itemId = DailyContent.itemId
    WHERE
    eventId=@eventId AND (weekDayId=@mon OR
            weekDayId=@tue OR
            weekDayId=@wed  OR
            weekDayId=@thu  OR
            weekDayId=@fri  OR
            weekDayId=@sat  OR
            weekDayId=@sun)
    GROUP BY DailyContent.dailyContentId, DailyContent.itemId, title, defaultSmallImagePath
    HAVING (COUNT(weekDayId) = @daysCount)
于 2013-04-12T12:18:54.213 回答
0

试试这个——

DECLARE @daysCount INT
SELECT @daysCount = 
    CASE WHEN @mon IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @tue IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @wed IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @thu IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @fri IS NOT NULL THEN 1 ELSE 0 END +
    CASE WHEN @sat IS NOT NULL THEN 1 ELSE 0 END + 
    CASE WHEN @sun IS NOT NULL THEN 1 ELSE 0 END 

SELECT dc.dailyContentId
FROM dbo.DailyContent dc
WHERE eventId = @eventId 
    AND weekDayId IN (@mon, @tue, @wed, @thu, @fri, @sat, @sun)
GROUP BY DailyContent.dailyContentId
HAVING COUNT(dailyContentId) = @daysCount
于 2013-05-17T17:08:37.930 回答