全连接(full JOIN)与计数(COUNT)查询出现问题,大家帮帮忙。
我又两个表,一个表是问题类型表(T_IssueType),数据如下:
IssueTypeID IssueTypeName
1 Bug
2 Feature
3 安装问题
4 使用问题
另一个表是事务表(T_TrackItem),主要字段如下:
TrackItemID IssueTypeID
1 1
2 1
3 2
4 3
5 NULL
6 NULL
我现在通过全连接来查看T_TrackItem中每个问题类型的个数,SQL语句如下
SELECT COUNT(dbo.T_TrackItem.IssueTypeID) AS TypeCount, dbo.T_IssueType.IssueTypeName, dbo.T_IssueType.IssueTypeIDFROM dbo.T_IssueType full JOIN dbo.T_TrackItem ON dbo.T_TrackItem.IssueTypeID = dbo.T_IssueType.IssueTypeIDGROUP BY dbo.T_IssueType.IssueTypeID, dbo.T_IssueType.IssueTypeName
SELECT COUNT(ISNULL(dbo.T_IssueType.IssueTypeID, 0)) AS TypeCount, ISNULL(dbo.T_IssueType.IssueTypeName, '暂无') AS IssueTypeName, ISNULL(dbo.T_IssueType.IssueTypeID, 0) AS IssueTypeIDFROM dbo.T_TrackItem full JOIN dbo.T_IssueType ON dbo.T_TrackItem.IssueTypeID = dbo.T_IssueType.IssueTypeIDGROUP BY dbo.T_IssueType.IssueTypeID, dbo.T_IssueType.IssueTypeName
------------------------------ Author :fredrickhu(小F,向高手学习)-- Date :2012-06-28 09:34:31-- Version:-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) -- Apr 22 2011 11:57:00 -- Copyright (c) Microsoft Corporation-- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)--------------------------------> 测试数据:[T_IssueType]if object_id('[T_IssueType]') is not null drop table [T_IssueType]go create table [T_IssueType]([IssueTypeID] int,[IssueTypeName] varchar(8))insert [T_IssueType]select 1,'Bug' union allselect 2,'Feature' union allselect 3,'安装问题' union allselect 4,'使用问题'--> 测试数据:[T_TrackItem]if object_id('[T_TrackItem]') is not null drop table [T_TrackItem]go create table [T_TrackItem]([TrackItemID] int,[IssueTypeID] int)insert [T_TrackItem]select 1,1 union allselect 2,1 union allselect 3,2 union allselect 4,3 union allselect 5,null union allselect 6,null--------------开始查询--------------------------select count(isnull(a.IssueTypeID,0)),b.IssueTypeName,a.TrackItemIDfrom [T_TrackItem] a left join [T_IssueType] bon a.IssueTypeID=b.IssueTypeIDgroup by b.IssueTypeName,a.TrackItemID----------------结果----------------------------/* IssueTypeName TrackItemID----------- ------------- -----------1 Bug 11 Bug 21 Feature 31 安装问题 41 NULL 51 NULL 6*/
[解决办法]