Multiple Condition with Groupby - sql

I am getting error wih following code, "Msg 144, Level 15, State 1, Line 17
Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
"
SELECT [sddoc],
[Soldtopt],
[tradingname],
[DlvDate],
SUM(try_cast(Netvalue AS FLOAT)) AS Netvalue,
COUNT(DISTINCT SDDoc) AS Salesdoc ,
COUNT(DISTINCT
CASE
WHEN Netvalue = '0'
THEN 1
ELSE NULL
END) AS ZeroValue ,
COUNT(DISTINCT SDDoc) - COUNT(DISTINCT
CASE
WHEN Netvalue = '0'
THEN 1
ELSE NULL
END) AS Result
FROM d1
WHERE dlvdate='25.01.2017'
GROUP BY
CASE
WHEN SUM(try_cast(Netvalue AS FLOAT)) = 0
AND COUNT(DISTINCT SDDoc) = 1
AND COUNT(DISTINCT
CASE
WHEN Netvalue = '0'
THEN 1
ELSE NULL
END) = 1
THEN [sddoc]
END,
Soldtopt,
tradingname,
DlvDate

You can't use SUM or COUNT (aggregates) in the GROUP BY clause. Aggregate values must be calculated after groups are defined.
Also, your CASE lacks an ELSE clause.

Related

PostgreSQL WHERE cause to filter out results with 0 causes a syntax error

I'm trying to produce a SQL query where I have my IDs on the first column, then sum of page hits of accounts in column 2 and page hits of payments in column 3. The below code works, except for one point. I want to exclude any rows which have 0 in accounts column. When I add in the WHERE clause
SELECT
EVAR3 AS MYID
sum(case when web.Page.name = 'Accounts:Overview' then 1 else 0 end) as accounts
sum(case when web.Page.name = 'Payment:Overview' then 1 else 0 end) as payments
FROM mytable
WHERE
timestamp >= to_timestamp('2021-09-01') AND timestamp <= to_timestamp('2021-09-02')
AND
(sum(case when web.Page.name = 'Accounts:Overview' then 1 else 0 end) > 0)
GROUP BY EVAR3
ORDER BY EVAR3 ASC
This gives me an invalid expression error on my where clause saying generate expressions are not valid in the where clause. When I change WHERE to HAVING I get a syntax error saying it expected EOF rather than GROUP.
How do I correctly implement a filter to remove results with 0 in accounts to otherwise working code?
Since it is an aggregate function it should be HAVING but it should appear after the GROUP BY. the structure is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
SELECT
EVAR3 AS MYID,
sum(case when web.Page.name = 'Accounts:Overview' then 1 else 0 end) as accounts,
sum(case when web.Page.name = 'Payment:Overview' then 1 else 0 end) as payments
FROM mytable
WHERE
timestamp >= to_timestamp('2021-09-01') AND timestamp <= to_timestamp('2021-09-02')
GROUP BY EVAR3
HAVING (sum(case when web.Page.name = 'Accounts:Overview' then 1 else 0 end) > 0)
ORDER BY EVAR3 ASC

SUM value when another column value is DISTINCT

I was wondering how I can SUM the values of a column based on another column's values being distinct like below. I tried the following two ways, each giving errors due to the aggregate function. I am trying to get NonDistinctTotals with the queries below.
SELECT SUM(InvoiceSaleAmt) AS NonDistinctTotals, SUM(case when count(*) over (partition by InvoiceNo) = 1 then InvoiceSaleAmt else 0 END) as DistinctTotals, SUM(CASE WHEN PaymentType= 'CASH' THEN CashTotal ELSE 0 END) AS CashTotal
FROM #InvoiceTable a
group by LocationId, InvoiceNo
Error: Windowed functions cannot be used in the context of another windowed function or aggregate.
SELECT SUM(InvoiceSaleAmt) AS NonDistinctTotals, SUM(CASE WHEN InvoiceNoin (SELECT DISTINCT InvoiceNofrom #InvoiceTable) THEN InvoiceSaleAmt else 0 END) as DistinctTotals, SUM(CASE WHEN PaymentType= 'CASH' THEN CashTotal ELSE 0 END) AS CashTotal
FROM #InvoiceTable a
group by LocationId, InvoiceNo
Error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Use a subquery:
SELECT SUM(InvoiceSaleAmt) AS NonDistinctTotals,
SUM(case when cnt = 1 then InvoiceSaleAmt else 0 END) as DistinctTotals,
SUM(CASE WHEN PaymentType = 'CASH' THEN CashTotal ELSE 0 END) AS CashTotal
FROM (SELECT it.*, COUNT(*) over (partition by InvoiceNo) as cnt
FROM #InvoiceTable it
) it
GROUP BY LocationId, InvoiceNo

SQL CASE WHEN THEN logics of calculating the types of a column

Have a tableA like this:
I wanna receive a tableŠ˜ like this (group by startTime and endTime, count of Severity in cnt column and count of every type of Severity in a distinct column):
The simple count (cnt column) works fine. But with the other I tired CASE WHEN THEN logics and it seems not working (line 10 for example). Can you please assist me with SQL query in this case.
You need conditional aggregation :
select starttime, endtime, count(*),
sum(case when severity = 'low' then 1 else 0 end),
sum(case when severity = 'med' then 1 else 0 end),
sum(case when severity = 'high' then 1 else 0 end)
from table t
group by starttime, endtime;
Try below query: with case when
select starttime, endtime, count(severity) as cnt, count(case when severity='LOW' then 1 end) cnt_low,count(case when severity='MED' then 1 end) cnt_med,count(case when severity='HIGH' then 1 end) as cnt_high
from tablename
group by starttime, endtime
use case when and aggregate function sum
select startTime , endTime,count(*) as Cnt,
sum( case when Severity='MED' then 1 else 0 end) as cntMed,
sum( case when Severity='LOW' then 1 else 0 end) as cntLow,
sum( case when Severity='HIGH' then 1 else 0 end) as cntHIGH from yourtable
group by startTime , endTime

SQL error when using outer grouping result to 'IN' operator in subquery

I have the following query which tries to use outer aggregation result as an input of subquery (in that case in statement):
select
COUNT(DISTINCT individual_id) as visitors,
(select
(case when
SUM(case when cr2.isConverted = true then 1 else 0 end) > 0
then 1 else 0 end) as conv from campaigns_reporting as cr2 where
cr2.id in (DISTINCT cr1.id) group by individual_id) as conversions
from campaigns_reporting as cr1 where
isinholdback = false and
occurredat between '2018-02-25T18:00:00.000Z' and '2018-03-04T17:59:59.000Z' and
customer_id = '1'
group by campaign_id, isinholdback
I am getting following error:
ERROR: syntax error at or near "DISTINCT"
LINE 5: ... from campaigns_reporting as cr2 where cr2.id in (DISTINCT
c...
^
Note: I'm using postgresql.
Thanks in advance for any kind of help.
Your query cannot be done. cr1 cannot use in the select the id because it's not included in the group by. So try this:
select COUNT(DISTINCT individual_id) as visitors,
(case when sum(cr3.conv) > 0 then 1 else 0 end) as conversions
from campaigns_reporting as cr1
inner join
(select id, (case when SUM(case when cr2.isConverted = true then 1 else 0 end) > 0 then 1 else 0 end) as conv
from campaigns_reporting as cr2
group by id) as cr3 on cr1.id= cr3.id
where isinholdback = false
and occurredat between '2018-02-25T18:00:00.000Z' and '2018-03-04T17:59:59.000Z'
and customer_id = '1'
group by campaign_id, isinholdback

How to have one row multiple columns instead of multiple rows

I have the following data:
In SQL Server How can I have group by weekdate so I have only one row for each weekdate, example for the weekdate 2015-11-14:
Any clue?
Use conditional aggregation.
select cast(weekdate as date),
sum(case when permittype = 0 then total else 0 end) as permittype0,
sum(case when permittype = 1 then total else 0 end) as permittype1
from tablename
group by cast(weekdate as date)
I would do this using conditional aggregation:
select weekdate,
sum(case when permittype = 0 then total else 0 end) as permitttype0,
sum(case when permittype = 1 then total else 0 end) as permitttype1
from followingdata t
group by weekdate
order by weekdate;
You can also use pivot syntax, if you prefer.