简体   繁体   English

第2条:不同的限制

[英]WHERE Clause 2 Different Restrictions

I have a table of data, and I wanted to make a WHERE clause with 2 different restrictions applying to the same variable. 我有一个数据表,我想制作一个WHERE子句,该子句有2个不同的限制适用于同一变量。 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. 我想使用汇总列来汇总所有价格,但是我不知道如何编写WHERE语句,该语句对SummedCost列使用PriceDescription LIKE'Cost。%',而对于PriceDescription LIKE'%。%'摘要列。

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'. 我试图将WHERE PriceDescription LIKE '%.%'SUM(Price) over(Partition by Location) AS SummedCost但出现了有关“ as”的错误。

Thanks for any help! 谢谢你的帮助!

Remove the WHERE clause, and use a CASE expression in the SUM() : 删除WHERE子句,并在SUM()使用CASE表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM