scenario: I have table A and Table B. Both have the primary key of Rep_time_frame. We replicate data by terms. however, that process at times was repeated.
task: Match the source counts with the destination table counts.
problem: I can match the rows of the source table but not the destination table because the replication for some terms happened twice. So, my counts are off.
SELECT d.REPT_TIME_FRAME,
c.SOURCE_TOTAL_RECORDS,
COUNT(*) TOTAL_RECORDS,
CASE
WHEN COUNT(*) > c.SOURCE_TOTAL_RECORDS THEN c.SOURCE_TOTAL_RECORDS
ELSE COUNT(*)
END FINAL_TOTAL_RECORDS,
***CASE
WHEN EXISTS (SELECT REPT_TIME_FRAME
FROM TableA_Counts
WHERE REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY REPT_TIME_FRAME
HAVING COUNT(*) > 1) THEN 'UPLOADED MORE THAN ONCE'
ELSE'UPLOADED ONCE'
END NUMBER_OF_REPLICATIONS***
FROM TableA d
INNER JOIN TableA_Counts c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
WHERE d.REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY d.REPT_TIME_FRAME, c.SOURCE_TOTAL_RECORDS```
please note that the bolded area, when ran returns for the newly made column Number_of_replications "Uploaded More than once" on all counts. For the purposes of this example. Here are the facts.
201705 was replicated 2X
201801 once and 201708 once.
expected result. I want to have 201705 'Uploaded more than once', and the rest 201801 and 201708 'Uploaded Once'
Does this help?
http://sqlfiddle.com/#!18/8692a/1
I always try and get the counts then do a case statement on the final figures. I've based that SqlFiddle on the notion that TableA_Counts is the table with more than one entry for 201705. Is that correct?
CREATE TABLE TableA (REPT_TIME_FRAME int)
INSERT INTO TableA(REPT_TIME_FRAME)VALUES
(201705),
(201708),
(201801),
(201706),
(201710),
(201803 )
CREATE TABLE TableA_Counts (REPT_TIME_FRAME int)
INSERT INTO TableA_Counts(REPT_TIME_FRAME)VALUES
(201705),
(201708),
(201705),
(201801),
(201706),
(201710),
(201803)
SELECT
d.REPT_TIME_FRAME,count(*) as TOTAL_RECORDS,SOURCE_TOTAL_RECORDS,
CASE WHEN SOURCE_TOTAL_RECORDS > 1 then 'more than' else 'just one' end as NUMBER_OF_REPLICATIONS
FROM
TableA d
LEFT JOIN
(SELECT REPT_TIME_FRAME ,count(*) as SOURCE_TOTAL_RECORDS from TableA_Counts group by REPT_TIME_FRAME) c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
group by d.REPT_TIME_FRAME,SOURCE_TOTAL_RECORDS
SELECT d.REPT_TIME_FRAME,
c.SOURCE_TOTAL_RECORDS,
COUNT(*) TOTAL_RECORDS,
CASE
WHEN COUNT(*) > c.SOURCE_TOTAL_RECORDS THEN c.SOURCE_TOTAL_RECORDS
ELSE COUNT(*)
END FINAL_TOTAL_RECORDS,
a.count AS NUM_OF_REPLICATIONS
FROM TableA d
INNER JOIN TableACounts c ON (d.REPT_TIME_FRAME = c.REPT_TIME_FRAME)
INNER JOIN (SELECT REPT_TIME_FRAME ,count(REPT_TIME_FRAME) as count
FROM TableAcounts
WHERE REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY REPT_TIME_FRAME) AS a ON (a.REPT_TIME_FRAME = d.REPT_TIME_FRAME)
WHERE d.REPT_TIME_FRAME IN (201705, 201708, 201801, 201706, 201710, 201803)
GROUP BY d.REPT_TIME_FRAME, c.SOURCE_TOTAL_RECORDS, a.count
Related
I want to produce a similar table that this table below.
In the first time, this table is create by another program but I must insert a new rows when an images is added.
For this, I have try this request but the select is done upstream of the insert and the Max function is useless.
#idart contains a table with multiple CODE and ID_IMG but without ORDER number.
INSERT INTO [NOMENC_ARTICLES_IMAGES]
SELECT
I.CODE, I.ID As ID_IMG,
CASE
WHEN (SELECT MAX(AI.ORDRE) FROM [NOMENC_ARTICLES_IMAGES] AS AI
WHERE AI.CODE = A.CODE) IS NULL
THEN 0
ELSE (SELECT MAX(AI.ORDRE) FROM [NOMENC_ARTICLES_IMAGES] AS AI
WHERE AI.CODE = A.CODE) + 1
END AS ORDER
FROM
#idart AS I
LEFT JOIN
[NOMENC_ARTICLES_IMAGES] AS A ON A.CODE = I.CODE
Could you help me to increment the ORDER column in terms of CODE and ID_IMG?
EDIT :
In [NOMENC_ARTICLES_IMAGES] I have :
And I want to add 1, 2, x value contains in #idart.
For exemple :
#idart :
The expected result after insert :
I hope that with this example, you will better understand my need
I think I've find the solution based on the answer of casenonsensitive :
INSERT INTO [NOMENC_ARTICLES_IMAGES]
SELECT I.CODE, I.ID As ID_IMG,
row_number() over (partition by I.CODE order by I.ID) +
CASE WHEN A.ORDER IS NULL THEN -1 ELSE A.ORDER END As ORDER
FROM
#idart AS I
LEFT JOIN
(SELECT AI.CODE, MAX(AI.ORDER) As ORDER FROM [NOMENC_ARTICLES_IMAGES] As AI GROUP BY AI.CODE) AS A ON A.CODE = I.CODE
Thanks for all !
Use an analytical function like this:
INSERT INTO [NOMENC_ARTICLES_IMAGES]
select I.CODE, I.ID As ID_IMG,
row_number() over (partition by I.CODE order by I.ID)
+ (select isnull(max(order), 0) from [NOMENC_ARTICLES_IMAGES] AS A ON A.CODE = I.CODE)
As ORDER
FROM
#idart AS I
But pay attention, that you're always getting the highest order for the highest I.ID per I.CODE. In some cases that works, in others I.ID would not have to be strictly growing. Meaning the newest images wouldn't get the biggest ORDER's
I am new to SQL and I have the below tables
that I need to select and get the desired result below.
Try a query like below.
select
[Account Group] =AG.Name,
[Ledger Name] =AL.Name,
DR =SUM(CASE WHEN TT.Name='DR' THEN Amount ELSE NULL END),-- case based SUM expression
CR =SUM(CASE WHEN TT.Name='CR' THEN Amount ELSE NULL END)
from Account_Group AG
join Account_ledgers AL -- NOTE we have used INNER JOIN throughout
on AG.Id=AL.AccountGroupId
join Transactions T
on T.AccountLedgerId=AL.Id
join Transaction_Type TT
on TT.Id= T.TransactionTypeId
group by AG.Name,AL.Name -- Group by contains all the things we need in SELECT list
I have two Identical table with different purpose each.
Table A
ID,TypeofAsset, Amount
1,C,300
2,A,40
3,F,90
Table B
ID,TypeofAsset,amount
1,G,500
2,A,20
3,C,150
Result with Query (Table A id= 1 compare with Table B ID =3)
Col, Result
TypeofAsset, match -- (C)
Amount, 150 --(Absolute value of Amount difference)
Any help will be appreciate.
Thanks
You can do a JOIN on TypeofAsset column like
select t1.TypeofAsset,
case when t1.Amount > t2.Amount then t1.Amount - t2.Amount
else t2.Amount - t1.Amount end as diff_amount
from tablea t1 join tableb t2 on t1.TypeofAsset = t2.TypeofAsset;
You can as well use ABS() function as commented like
select t1.TypeofAsset,
ABS(t1.Amount - t2.Amount) as diff_amount
from tablea t1 join tableb t2 on t1.TypeofAsset = t2.TypeofAsset;
Hi I have the below working query(mssql)
select
max(load_number) load_number,max(linediscount) maxlinediscount,max(CustomerBand) customer_band
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
join price_escalation_bands
on price_escalation_bands.band=Customer_Order_Summary.CustomerBand
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='7'
)
and Customer_Order_lines.linestatus='current'
group by load_number
This produces the result
In this query, I have already joined to the table price_escalation_bands which looks like this:
What I am wanting to do, is compare the maxlinediscount from my query with the discount column of table price_escalation_bands and return the user id (fk_salesman_userid) of the record in the table that is the next greatest. so discount of 11 would go to discount 15 and return fk_salesman_userid 9. if the discount was 18, it would go to 100 and return fk_salesman_userid 21.
I am basically trying to work out the fk_salesman_userid that can approve the discount in maxlinediscount
So desired output would be:
Do I need a case statement and if so how do I use it with the max statements in my existing select statement?
thanks in advance as aways
While joining the price_escalation_bands you can use one more condition for discount.
Check the FIDDLE. Here I have tried with the result in a temp table. You can try the same subquery with your join price_escalation_bands by passing the max(linediscount).
Hope this will help you.
Final Working syntax:
IF OBJECT_ID('tempdb..#linkloads') IS NOT NULL
BEGIN
DROP TABLE #linkloads
END
CREATE TABLE #linkloads
(
maxlinediscount [decimal](10,3),
customer_band [varchar](50),
load_number [int],
totalcost [decimal](10,3),
period [datetime],
CreditLimit[decimal](10,3),
CurrentBalance[decimal](10,3),
CustomerName [varchar](100),
TotalCubes[decimal](10,3),
TreatedCubes[decimal](10,3),
NormalCubes[decimal](10,3),
PricingIssue[bit]
);
insert into #linkloads
select max(linediscount) maxlinediscount,max(CustomerBand) customer_band,max(load_number) load_number,max(totalcost) totalcost,max(Customer_Order_Summary.PeriodStart) period,max(Customers.CreditLimit) CreditLimit ,max(Customers.CurrentBalance)CurrentBalance,max(Customer_Order_Summary.CustomerName)CustomerName,max(TotalCubes) TotalCubes,max(TreatedCubes)TreatedCubes ,max(TotalCubes-TreatedCubes) as NormalCubes,sum(case when pricingissue=1 THEN 1 ELSE 0 END) pricingissue
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='10'
)
and Customer_Order_lines.linestatus='current'
group by load_number;
select * from #linkloads;
select load_number,maxlinediscount,customer_band,[Salesman_Discounts_per_band].fk_salesman_userid,totalcost,period,creditlimit,currentbalance,customername,totalcubes,treatedcubes,normalcubes,pricingissue from #linkloads
left outer JOIN [Salesman_Discounts_per_band] on [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed] = (
SELECT top 1 [Salesman_Discounts_per_band].[discount_allowed]
FROM [Salesman_Discounts_per_band]
WHERE [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed]<=#linkloads.maxlinediscount
ORDER BY [Salesman_Discounts_per_band].[discount_allowed]
)
;
Good Morning All
My boss helped me design a query where it populates 1.37 million lines of random data, he has now asked me to insert/update the results into a blank table. But for some reason I cannot get it to work.
The three columns are ArrivalDate, PitchType_Skey and Site_Skey. But when I run my query (See below) I get an error message and I don't know why. Can you help?
Msg 121, Level 15, State 1, Line 2
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
Query:
USE Occupancy
INSERT INTO Bookings (ArrivalDate, Site_Skey, PitchType_Skey)
SELECT
Time.Date, Site.Site_Skey, Site.SiteWeighting, PitchType.PitchType_Skey,
PitchType.PitchTypeWeighting,
RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting AS Expr1
FROM
Capacity
INNER JOIN
Site ON Capacity.Site_Skey = Site.Site_Skey
INNER JOIN
PitchType ON Capacity.PitchType_Skey = PitchType.PitchType_Skey
INNER JOIN
Time
INNER JOIN
AGKey ON Time.ArrivalDayWeighting = AGKey.[Key] ON Capacity.StartDate <= Time.Date AND Capacity.EndDate >= Time.Date
CROSS JOIN
(SELECT 0 AS col1
UNION ALL
SELECT 1 AS col1) AS aaav
WHERE
(Time.CalendarYear = 2010)
AND (RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting >= 1.22)
Thanks
Wayne
The error message give you the answer. You have more items in your SELECT list (6)
Time.Date
Site.Site_Skey
Site.SiteWeighting
PitchType.PitchType_Skey
PitchType.PitchTypeWeighting
RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting AS Expr1
Than you do in your INSERT list (3)
ArrivalDate
Site_Skey
PitchType_Skey
Either remove some columns from your SELECT list or add some to your INSERT list.
As you haven't given the complete structure of your Bookings table I can only guess that you will need to do this
USE Occupancy
INSERT INTO Bookings
(
ArrivalDate,
Site_Skey,
PitchType_Skey
)
SELECT
Time.Date,
Site.Site_Skey,
PitchType.PitchType_Skey
FROM
Capacity
INNER JOIN Site ON Capacity.Site_Skey = Site.Site_Skey
INNER JOIN PitchType ON Capacity.PitchType_Skey = PitchType.PitchType_Skey
INNER JOIN Time
INNER JOIN AGKey ON Time.ArrivalDayWeighting = AGKey.[Key] ON Capacity.StartDate <= Time.Date AND Capacity.EndDate >= Time.Date
CROSS JOIN
(
SELECT 0 AS col1
UNION ALL
SELECT 1 AS col1
) AS aaav
WHERE
Time.CalendarYear = 2010
AND (RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting >= 1.22)
I have found the solution and I cant believe how easy it was, I just un-ticked the boxes I didn't want on the Query Designer.