对列的每个不同值执行CRUD操作

时间:2016-10-21 11:06:28

标签: sql-server

我想要实现的是选择可以通过

完成的列的不同值
select distinct B_id as beauName from tbl_addbill WHERE forUser='sun4269' 

然后对于每个不同的B_id我想执行此查询

IF EXISTS (SELECT * FROM tbl_addbill WHERE forUser='sun4269' and bill_no='2015-2016' and B_id='Bhavik Creation-1')
BEGIN
    select 1;
END 
ELSE
BEGIN
    insert into tbl_addbill(bill_no,B_id,amount,tax,amount_paid,forUser,bill_date)
        values 
        (
            '2015-2016',
            'Bhavik Creation-1',
            (
                select COALESCE(sum(amount),0) 
                    from tbl_addbill 
                    where forUser='sun4269' and B_id='BhavikCreation-1' 
                        and bill_date between '2015-04-01' and '2016-03-31'
            ),
            (
                select COALESCE(sum(tax),0)
                    from tbl_addbill
                    where forUser='sun4269' and B_id='BhavikCreation-1' 
                        and bill_date between '2015-04-01' and '2016-03-31'
            ),
            (
                select COALESCE(sum(amount_paid),0) 
                    from tbl_addbill
                    where forUser='sun4269' and B_id='BhavikCreation-1' 
                        and bill_date between '2015-04-01' and '2016-03-31'
            ),
            'sun4269',
            getdate()
        );
    select 2;
END;

目前我的两个查询都运行正常,但我想要的是将两者结合起来,首先从tbl_addbill中选择不同的B_id,然后执行第二个查询,就像不同的列表一样多次。当前我的第二个查询适用于'BhavikCreation-1'仅我和我想用不同的列表替换它,我的第二个查询的作用是计算2015-04-01到2016-03-31期间金额,税金,amount_paid的总和并插入一个进入表格的新行

其次我多次使用相同的where子句,有没有办法减少它

1 个答案:

答案 0 :(得分:0)

使用GROUP BY子句尝试此查询:

insert into tbl_addbill(bill_no,B_id,amount,tax,amount_paid,forUser,bill_date)
    select '2015-2016',
            B_id,
            COALESCE(sum(IIF(bill_date between '2015-04-01' and '2016-03-31', amount,      0)), 0),
            COALESCE(sum(IIF(bill_date between '2015-04-01' and '2016-03-31', tax,         0)), 0),
            COALESCE(sum(IIF(bill_date between '2015-04-01' and '2016-03-31', amount_paid, 0)), 0),
            forUser,
            getdate()
        from tbl_addbill
        where forUser = 'sun4269'
        group by B_id;

IF @@ROWCOUNT = 0
    select 1;
ELSE
    select 2;