I'm struggling to do something in SQL Server that is super easy in 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:
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?
Unlike MySQL, SQL Server does not assume what columns you want to group by. Every column that is not being aggregated needs to be defined in the GROUP BY
list.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.