我有一个类似于下面的查询,它显示了几个表的记录计数。
SELECT 'SomeTable' as tname, COUNT(*) as ttlRecords FROM SomeTable WHERE SubjectID = @SubjectID
UNION
SELECT 'AnotherTable' as tname, COUNT(*) as ttlRecords FROM AnotherTable WHERE SubjectID = @SubjectID
UNION
SELECT 'YetAnotherTable' as tname, COUNT(*) as ttlRecords FROM YetAnotherTable WHERE SubjectVersionID = @SubjectVersionID
结果看起来像这样......
tname ttlRecords
SomeTable 25
AnotherTable 55
YetAnotherTable 120
现在,我想修改它以进一步显示特定条件下的一些计数。对于此示例,我有一个 RegionID,它指定记录是与加拿大还是美国区域相关联。因此,我想将 USRecordCount 和 CARecordCount 与 ttlRecordCount 显示在同一行,如下所示...
tname ttlRecords USRecordCount CARecordCount
SomeTable 25 10 15
AnotherTable 55 52 3
YetAnotherTable 120 100 20
我知道我可以使用子查询来做到这一点,如下所示,但它看起来很草率而且可能很慢。
SELECT
'SomeTable' as tname,
(SELECT COUNT(*) FROM SomeTable WHERE SubjectID = @SubjectID) as ttlRecords,
(SELECT COUNT(*) FROM SomeTable WHERE SubjectID = @SubjectID AND RegionTypeID = 1) as USRecordCount,
(SELECT COUNT(*) FROM SomeTable WHERE SubjectID = @SubjectID AND RegionTypeID = 2) as CARecordCount
UNION
SELECT
'AnotherTable' as tname,
(SELECT COUNT(*) FROM AnotherTable WHERE SubjectID = @SubjectID) as ttlRecords,
(SELECT COUNT(*) FROM AnotherTable WHERE SubjectID = @SubjectID AND RegionTypeID = 1) as USRecordCount,
(SELECT COUNT(*) FROM AnotherTable WHERE SubjectID = @SubjectID AND RegionTypeID = 2) as CARecordCount
UNION
SELECT
'YetAnotherTable' as tname,
(SELECT COUNT(*) FROM YetAnotherTable WHERE SubjectVersionID = @SubjectVersionID) as ttlRecords,
(SELECT COUNT(*) FROM YetAnotherTable WHERE SubjectVersionID = @SubjectVersionID AND RegionTypeID = 1) as USRecordCount,
(SELECT COUNT(*) FROM YetAnotherTable WHERE SubjectVersionID = @SubjectVersionID AND RegionTypeID = 2)as CARecordCount
我的问题是,有没有更好的方法来写这个?