-1

我谦虚地寻求下一个问题的帮助。

我有这个非常简单。不知道如何用文字来形容,所以我会用图像来做。

餐桌服务

PERSONID     Service_id          chargeamount
1               3                 20.50
2               4                 80.50
3               5                 78.80

餐桌费用

service_id     payed          extracharges
3               true              20.50
4               true              80.50
3               false             78.80

如果有任何未支付的额外费用,它必须显示 true 或 false ,并且如果服务 ID 在第二个表中不匹配,则它必须在查询中显示为空值或其他计算值

像这样的东西

PERSONID     Service_id          chargeamount                        payed
1               3                 20.50                              false
2               4                 80.50                              true
3               5                 78.80                              null

但是同一行的额外行不允许像连接创建的行一样。

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[SERVICES](
    [personid] [int] NULL,
    [service_id] [int] NULL,
    [chargeamount] [float] NULL
) ON [PRIMARY]

GO


insert into services (personid,service_id,chargeamount) values ( 1,3  ,20);
insert into services (personid,service_id,chargeamount) values ( 2,4  ,20);
insert into services (personid,service_id,chargeamount) values ( 3,5 ,20);



SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[charges](
    [payed] [bit] NULL,
    [service_id] [int] NULL,
    [extracharges] [float] NULL
) ON [PRIMARY]

GO

insert into services (service_id,payed,extracharges) values ( 3,true,20.50);
insert into services (service_id,payed,extracharges) values ( 3,false,78.80);
insert into services (service_id,payed,extracharges) values ( 4,false,80.50);
4

1 回答 1

0

这是一个简单的左连接service_id。当至少有一行带有payed=false时,false显示。否则分别显示true或。null

select s.*, case min(c.payed) when 1 then 'true' when 0 then 'false' else 'null' end
from services s
left join charges c on c.service_id = s.service_id
group by s.personid, s.service_id, s.chargeamount

SQLFiddle

于 2013-01-24T19:02:56.913 回答