'Error: An expression of non-boolean type specified in a context where a condition is expected, near ')' SQL Server
Question built from this question (Still return records if unsatisfied cross join condition). The database for this question is extended and provided below.
My desired output is to show the first four things bought in a month, and if bought on the same day, output the one with a larger amount.
I have added d_thing_id to see which thing, bought on the same day, has a larger amount.
However, I keep getting an error
An expression of non-boolean type specified in a context where a condition is expected, near ')'
Data:
create table Sales
(
Date datetime,
C_Name char(1),
Thing varchar(100),
Amount int
)
insert into Sales (Date, C_Name, Thing, Amount)
values ('2021-02-21','A','Fruit', 20)
,('2021-02-22','A','Bottle', 15)
,('2021-02-22','A','Straw', 7)
,('2021-02-26','A','Doll' , 31)
,('2021-02-27','A','Drink', 29)
,('2021-02-27','A','Bread', 30)
,('2021-02-28','B','Book' , 67)
,('2021-06-03','B','Fruit' , 100)
,('2021-06-13','B','Shoes' , 10)
,('2021-06-10','C','Shoes', 90)
,('2021-07-07','A','Tablet', 4)
,('2021-07-11','A','Chair' , 77)
,('2021-07-11','A','Cushion', 43)
,('2021-07-20','A','Sofa' , 37)
,('2021-07-21','A','Coat' , 66)
Code
with d1(Date, C_Name, Thing, Amount, Month) as
(
select *, month(Date) as Month
from Sales
),
d2 (thing_id, Month, C_Name, Thing) as
(
select
'Thing' + cast(row_number() over (partition by C_Name, Month
order by Date) as varchar(10)) as thing_id
,Month
,C_Name
,Thing
from d1
where
(select row_number() over (partition by C_Name, Month, Date
order by Date, Amount desc) as d_thing_id
from d1
where d_thing_id = 1)
)
select *
from d2
pivot
(min(Thing)
for thing_id in ([Thing1], [Thing2], [Thing3])
) as p;
EDIT
My expected output
month C_Name Thing1 Thing2 Thing3 Thing4
2 A Fruit Bottle Doll Bread
2 B Fruit
6 B Fruit Shoes
6 C Shoes
7 A Tablet Chair Sofa Coat
Solution 1:[1]
this where clause has no operator
where (select row_number() over
(
partition by C_Name, Month, Date
order by Date, Amount DESC
) as d_thing_id
from d1
where d_thing_id = 1
)
It should be more like this for example
where (select row_number() over
(
partition by C_Name, Month, Date
order by Date, Amount DESC
) as d_thing_id
from d1
where d_thing_id = 1
) = something
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GuidoG |
