I have a table of data, and I wanted to make a WHERE clause with 2 different restrictions applying to the same variable. I cannot figure out a way to apply it though.
This is my current table (MINUS THE SUMMARY COLUMN THAT IS MY GOAL)
ID Location Price PriceDescription SummedCost Summary
1 Park -10 Cost.Water -18 -7
1 Park -8 Cost.Gas
1 Park 11 Sold.Price
2 Tom 20 Sold.Price -6 14
2 Tom -6 Cost.Soap
3 Matt -15 Cost.Tools -30 -9
3 Matt -15 Cost.Gas
3 Matt 21 Sold.Price
4 College 32 Sold.Price -22 21
4 College -22 Cost.Water
4 College 11 Sold.LateFee
My code is
SELECT ID
,Location
,Price
,PriceDescription
,SUM(Price) over(Partition by Location) AS SummedCost
FROM
table
WHERE
PriceDescription LIKE 'Cost.%'
And this is where I run into problems. I would like to have the summary column which sums all of the prices, but I do not know how to write a WHERE statement that says the PriceDescription LIKE 'Cost.%' for the SummedCost column and PriceDescription LIKE '%.%' for the Summary column.
Is this possible? I tried to add the WHERE PriceDescription LIKE '%.%'
to SUM(Price) over(Partition by Location) AS SummedCost
but I got an Error Regarding the 'as'.
Thanks for any help!
Remove the WHERE
clause, and use a CASE
expression in the SUM()
:
SELECT ID
,Location
,Price
,PriceDescription
,SUM(Case When PriceDescription Like 'Cost.%'
Then Price
Else 0
End) Over(Partition by Location) AS SummedCost
,SUM(Price) Over(Partition by Location) As Summary
FROM table
您可以在以下情况下使用案例:
,SUM(case when PriceDescription like 'Cost.%' then Price else 0 end) over(Partition by Location) AS SummedCost
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.