使用 SQL Server 2008。
大家好,我有一张桌子,Language
我需要这张桌子是LanguageID
(1-10)。
我有另一张桌子UserQuiz
,我需要ModuleID
通过COUNT()
。
该计划是展示 10 种语言和 4 个模块,用户通过计数。
所以它将是 40 条记录(LanguageIDs * ModuleIDs)。
但并非所有语言都有所有模块,因此没有任何记录。
我需要一个查询,它只填写缺少的模块并将 null 放入用户计数的记录中。
到目前为止,我已经尝试...
更新:: 29/08/2013 @ 10:35 am (GMT)。
CREATE TABLE #CrossTable(
LanguageID int,
ModuleID int
)
INSERT INTO #CrossTable
SELECT LanguageID, ModuleID
FROM
RoundupAcademy.dbo.Languages
CROSS JOIN
RoundupAcademy.dbo.CurrentModules
/*********************************************************************************/
/** get users via date and quiz **************************************************/
CREATE TABLE #userspassed(
userid int,
passed int,
moduleid int,
languageid int
)
INSERT INTO #userspassed
SELECT userprofile.UserId, passed, userquiz.moduleID, LanguageId
FROM
UserProfile
LEFT JOIN
UserQuiz
ON
UserProfile.UserId = UserQuiz.userID
WHERE
((Convert(datetime,LastLogin, 120) >=
Convert(datetime,@datefrom, 120)
AND (Convert(datetime,LastLogin, 120) <=
convert(datetime,@datetoo, 120))))
AND
(passed is null or passed = 1)
/*********************************************************************************/
/**Get Modules per language count on users passed ********************************/
SELECT
#CrossTable.languageID,
#CrossTable.ModuleID,
coalesce(COUNT(#userspassed.userID),0) as users
FROM
#CrossTable
LEFT JOIN
#userspassed
ON
#CrossTable.ModuleID = #userspassed.moduleID
GROUP BY #CrossTable.LanguageID, #CrossTable.ModuleID
/*********************************************************************************/
this does bring back 40 records but module "n" that is repeated 10 times for language also has repeated Users(count). seems there is only 4 values that is being applied to 10 of the languages for module 1 (value 94) and 10 for module 2 (value 89) and 10 for module 3 (value 104) and 10 for module 4 (value 28).
Each record should be different but it seems its applying the same values to all modules that are the same.
UPDATED:: 29/08/2013 @ 11:05 am (GMT).
I forgot to add
AND
#CrossTable.LanguageID = #userspassed.languageid
seems to work now just going to check the values are correct