问题
The embarassing fiddle for the entire question can be found here. Basically I have three tables containing invoice information:
CREATE TABLE billing
([bill_id] varchar(5), [bill_reference_id] varchar(8), [bill_date] date, [billing_type] varchar(1))
CREATE TABLE billing_detail
([bill_id] varchar(5), [accpac_category_type] varchar(1), [location_id] varchar(1))
CREATE TABLE locations
([location_id] varchar(1), [location] varchar(50))
;
Invoices can have two billing_types I and C (invoice and credit). There can be multiples invoices or credits for any client (bill_reference_id) in any given day.
I am trying to count the number multiple invoices and credits per client per day versus the number of single invoices per client per day (for the purposes of this exercise a credit counts as -1 and an invoice counts as 1). There are some additional criteria, one of the field - accpac_category_type - has to fall within specified parameters.
The resulting query is to be "pivoted" by a number of locations. Just to make it a little bit more difficult, one of the locations should be merged with another one.
My query works fine but it looks very untidy with 2-deep subqueries running under the main query. I'm sure there are more elegant ways for getting the same result. Any hints and ideas will be much appreciated.
SELECT main.date,
SUM (CASE main.location WHEN 'Loc1' THEN main.single ELSE NULL END) as 'Loc1 Single',
SUM (CASE main.location WHEN 'Loc1' THEN main.multiple ELSE NULL END) as 'Loc1 Multiple'
.
.
.
SUM (CASE main.location WHEN 'Loc4' THEN main.multiple ELSE NULL END) as 'Loc1 Multiple'
FROM (
SELECT sub.date,
sub.location,
SUM (CASE WHEN sub.Services<2 THEN 1 ELSE NULL END) as 'Single',
SUM (CASE WHEN sub.Services>1 THEN 1 ELSE NULL END) as 'Multiple'
FROM (
SELECT CAST(YEAR(bi.bill_date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(bi.bill_date) AS VARCHAR(2)), 2) AS 'Date',
bi.bill_reference_id,
CASE WHEN lo.location = 'Loc10' THEN Loc4' ELSE lo.location END as 'Location',
SUM (CASE bi.billing_type WHEN 'I' THEN 1 ELSE -1 END) as 'Services'
FROM billing bi, billing_detail bd, locations lo
WHERE bi.bill_id = bd.bill_id AND bd.location_id = lo.location_id
AND (bi.billing_type='I' OR bi.billing_type='C')
AND (bd.accpac_category_type='F' OR bd.accpac_category_type='S')
GROUP BY
CAST(YEAR(bi.bill_date) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH(bi.bill_date) AS VARCHAR(2)), 2),
bi.bill_reference_id,
location) AS sub
GROUP BY
date,
location) as main
GROUP BY
main.date
来源:https://stackoverflow.com/questions/58056176/count-instances-of-multiple-invoices-and-pivot-on-location