我一直在努力实现条件Where和遇到问题。我想做的只是选择那些去过美容院的客户,这些美容院在过去的一年里都有理发和修指甲。治疗不必在同一天进行。例如如果Susan在过去的12个月内修指甲,请选择Susan在同一时间内理发的所有时间。该表的结构是每次访问都是一行。 e.g。
Customer Treatment Treatment_Date
Susan Manicure 12 Jan 2013
Susan Make-up 3 Feb 2013
Susan Haircut 14 Feb 2013
Susan Blow Dry 3 Mar 2013
Susan Haircut 21 Apr 2013
Betty Manicure 4 Jun 2013
Betty Haircut 7 July 2013
Tara Haircut 10 Aug 2013
理想情况下,我想选择苏珊和贝蒂。这可以在一个查询中完成,还是必须分解,比如先选择所有理发的客户,然后从中选择那些有修指甲的客户。
提前感谢您的建议。
:)
答案 0 :(得分:1)
另一种解决方法
SELECT DISTINCT Customer
FROM
(
SELECT Customer,
MAX(CASE WHEN Treatment = 'Manicure' THEN 1 ELSE 0 END)
OVER (PARTITION BY Customer) had_manicure,
MAX(CASE WHEN Treatment = 'Haircut' THEN 1 ELSE 0 END)
OVER (PARTITION BY Customer) had_haircut
FROM table1 t
WHERE Treatment_Date >= DATEADD(month, -12, GETDATE())
) q
WHERE had_manicure + had_haircut = 2
输出:
| CUSTOMER | |----------| | Betty |
这是 SQLFiddle 演示
答案 1 :(得分:0)
这是“set-within-sets”子查询的示例。我想使用group by
和having
来解决这些问题:
select ct.Customer
from CustomerTreatment ct
where ct.Treatment_Date >= getdate() - 365
group by ct.Customer
having sum(case when ct.Treatment = 'Manicure' then 1 else 0 end) > 0 and
sum(case when ct.Treatment = 'Haircut' then 1 else 0 end) > 0;
having
子句中的每个条件都计算每种类型的治疗次数。您的条件指定每个至少出现一次,因此> 0
。
答案 2 :(得分:0)
Select Customer, Treatment, Treatment_Date From Treatments
Where Customer In (Select Customer from Treatments Where Treatment = 'Manicure' And Treatment_Date >= Start_Date_For_The_Period_Goes_Here And Treatment_Date <= End_Date_For_The_Period_Goes_Here)
And
Customer In (
Select Customer from Treatments Where Treatment = 'Haircut' And Treatment_Date >= Start_Date_For_The_Period_Goes_Here And Treatment_Date <= End_Date_For_The_Period_Goes_Here
)
在其他新闻中,我不会将此称为条件Where声明。如果Where子句包含Case When Then End短语,我会称之为。
答案 3 :(得分:0)
你可以做这样的事情
选择 顾客,
count(case when treatment = 'manicure' then 1 else 0 end) as Manicure,
count(case when treatment = 'haircut' then 1 else 0 end) as haircut
来自
customerTreatment
其中Treatment_date&gt; = DATEADD(年,-1,GetDate())
group by Treatment
have count(Manicure) > 1 and count(haircut) > 1