I am trying to run this subquery in SQL Server management Studio 2016 but it errors. It works in MySQL. Please advise:
select count(distinct company)
from
(
select company, sum(net_value_gbp) as last2yr_spend
from Orders
where bill_date >='01-Jan-2016'
group by company)
where last2yr_spend >50
alias your subquery like as below
SELECT COUNT(DISTINCT company)
FROM
(
SELECT company,
SUM(net_value_gbp) AS last2yr_spend
FROM Orders o
WHERE bill_date >= '01-Jan-2016'
GROUP BY company
) A
WHERE A.last2yr_spend > 50;
Do it like below :
select count(distinct company)
from
( select company, sum(net_value_gbp) as last2yr_spend
from Orders
where bill_date >= '01-Jan-2016'
group by company )
AS T1
where T1.last2yr_spend > 50
You have to use an ALIAS
for the sub query in sql server.
The alias is one issue. But, you should write the query like this:
select count(*)
from (select company, sum(net_value_gbp) as last2yr_spend
from Orders o
where bill_date >= '2016-01-01'
group by company
) c
where last2yr_spend > 50;
Notes:
COUNT(DISTINCT)
is not needed. The subquery returns one row per company. COUNT(DISTINCT)
incurs extra overhead, so a simple COUNT(*)
is sufficient. COUNT(company)
(instead of COUNT(*)
) if company
were ever NULL
*and you did not want to count it.select count(company)
from
(
select company, sum(net_value_gbp) as last2yr_spend
from Orders
where bill_date >='01-Jan-2016'
group by company
having sum(net_value_gbp) > 50) as T1
An alternative to subqueries is CTE, which I find slightly more readable. Something like the following:
;with orders_by_comp as (
select company, sum(net_value_gbp) as last2yr_spend
from Orders o
where bill_date >= '2016-01-01'
group by company)
select count(distinct company)
from orders_by_comp
where last2yr_spend > 50;
You can do the filtration on the sum using having
like this:
with cte
AS
(
select company
from Orders
where bill_date >='01-Jan-2016'
group by company
having sum(net_value_gbp) > 50
)
select count(distinct company)
from cte;
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.