[英]T-SQL equivalent to MySQL aggragate from other table
I'm struggling to do something in SQL Server that is super easy in MySQL. 我正在努力在SQL Server中做一些在MySQL中超级简单的事情。
I want to grab some columns (let's just say one for simplicity) from one table and then a count other columns of another table based on a key from the first table and have both values in my result set. 我想从一个表中获取一些列(为简单起见,只说一个),然后根据第一个表中的键对另一个表的其他列进行计数,并在我的结果集中包含这两个值。
The following query works in MySQL but does not in SQL Server: 以下查询在MySQL中有效,但在SQL Server中不适用:
SELECT
ph.PONum,
COUNT(pd.POLine) AS LineCount
FROM
POHeader AS ph
INNER JOIN
PODetail AS pd ON ph.POnum = pd.PONum
WHERE
ph.PONum = 4444
Results: 结果:
What is the SQL Server (T-SQL) way to do this? SQL Server(T-SQL)执行此操作的方式是什么?
Unlike MySQL, SQL Server does not assume what columns you want to group by. 与MySQL不同,SQL Server不会假定要分组的列。 Every column that is not being aggregated needs to be defined in the
GROUP BY
list. 需要在
GROUP BY
列表中定义每个未聚合的列。
For your query it should be: 对于您的查询应为:
SELECT
ph.PONum,
COUNT(pd.POLine) AS LineCount
FROM
[Dbo].POHeader AS ph
INNER JOIN
[Dbo].PODetail AS pd ON ph.POnum = pd.PONum
WHERE
ph.PONum = 4444
GROUP BY
ph.PONum
You can also use a correlated subquery. 您也可以使用相关子查询。 EG
例如
SELECT
ph.PONum,
( select COUNT(*) from PODetail where PONum = ph.POnum ) LineCount
FROM
POHeader ph
WHERE
ph.PONum = 4444
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.