1

我正在尝试使用 MSSQL 做一些我认为可能(很容易)的事情,但我不知道如何发出正确的搜索字符串。我有以下情况。

Table A
UID  | Value....
1    | a
2    | b
3    | c


Table B
PartTypes_uid_fk   | Value....
1           | a
1           | b
1           | c
1           | d
1           | e
3           | 67
3           | 1354

我试图得到以下结果,查询表 A 的所有结果 {TableA.*} 并在同一行结果显示表 b 引用的数量 {count TableB.tableA_fk} 到目前为止我所拥有的如下。

SELECT DISTINCT t1.uid, CONVERT(varchar(MAX), t1.Name) AS Name, CONVERT(varchar(MAX), t1.Description) AS Description, Count(t2.Items_uid_fk) OVER (Partition By t2.PartTypes_uid_fk) as Count FROM [Table1] as t1 left outer join Table2 as t2 on t2.PartTypes_uid_fk=t1.uid;

这适用于表 B 中具有关联记录的所有表 A 记录,但如果表 B 中有 0 个条目,它将不起作用。由于它们是 ntext 格式并且它是不同的,因此需要转换 varchars。

感谢您提前提供的所有帮助。斯蒂芬

4

3 回答 3

1

与其遇到GROUP BY on N/TEXT列问题并运行得更快,不如预先聚合 B 表并将其与 A 进行 LEFT JOIN。

select t1.*, ISNULL(t2.c, 0) AS CountOfB
from table1 t1
left join
(
    select parttypes_uid_fk, count(*) c
    from table2
    group by parttypes_uid_fk
) t2 on t2.PartTypes_uid_fk=t1.uid
于 2012-11-08T19:38:44.297 回答
0

比这更容易:

SELECT t1.uid, t1.Name, COUNT(*)
FROM [Table1] t1
LEFT JOIN [Table2] t2 ON t2.PartTypes_uid_fk = t1.uid
GROUP BY t1.uid, t1.Name
于 2012-11-08T19:37:44.797 回答
0

您的查询应该是

SELECT t1.uid, 
CONVERT(varchar(MAX), t1.Name) AS Name, 
CONVERT(varchar(MAX), t1.Description) AS Description, 
Count(t2.Items_uid_fk) CountItems 
FROM [Table1] as t1 left outer join Table2 as t2 on t1.uid = t2.PartTypes_uid_fk
GROUP BY uid, t1.name, t1.Description;
于 2012-11-08T19:38:14.813 回答