SQL: number of rows with specific value's (dynamic) - sql-server

Hard to explain problem here :)
I need to get a new column I have the amount of lines
F.E. "RIT-17000263-T: 1" would have an extra column "Total Sequences": '9'
"RIT-17000264-T: 1" would be "Total Sequences": '2'
Any help is welcome!:
SELECT DISTINCT
CONCAT(R.[Trip No_],'-', CONCAT('T: ', LEFT(R.[Partial trip Line No_],1))) AS 'TRIP',
R.[File] AS 'FILE',
R.[Sequence No_] AS 'SEQUENCE IN PTRIP'
FROM
[Route] AS R
WHERE
(R.[Trip No_] = 'RIT-17000263'
OR R.[Trip No_] = 'RIT-17000264')
GROUP BY
CONCAT(R.[Trip No_], '-', CONCAT('T: ', LEFT(R.[Partial trip Line No_],1))),
R.[File], R.[Sequence No_]

Perhaps wrap it in a CTE...
with cte as(
SELECT DISTINCT
CONCAT(R.[Trip No_],'-', CONCAT('T: ', LEFT(R.[Partial trip Line No_],1))) AS 'TRIP',
R.[File] AS 'FILE',
R.[Sequence No_] AS 'SEQUENCE IN TRIP'
FROM
[Route] AS R
WHERE
(R.[Trip No_] = 'RIT-17000263'
OR R.[Trip No_] = 'RIT-17000264')
GROUP BY
CONCAT(R.[Trip No_], '-', CONCAT('T: ', LEFT(R.[Partial trip Line No_],1))),
R.[File], R.[Sequence No_])
select
c.TRIP,
c.[FILE],
c.[SEQUENCE IN TRIP],
c2.CT as [Total Sequences]
from
cte c
join (select TRIP, count(TRIP) as CT from cte group by TRIP) c2 on c2.TRIP = c.TRIP

Related

SSRS Highlight Duplicate Values in Column Across Entire Report

I have an SSRS report that looks at products used in a bill of materials. It lists the items involved, the bill of materials (BOM) they belong to and other various information. I would like to highlight ANY duplicates in the item column without having to sort by item.
Example data:
Level
Item No.
BOM No.
Quantity Per
1
001468
017998
4
1
001850
017998
6
1
017663
017998
2
1
017792
017998
2
2
001468
017663
3
So in the above data, the item # "001468" should get highlighted even though the information in the other columns is different per row.
I am aware of the "Previous" function but I don't want to re-order the item number column so I don't think using that is an option
The report sorts by level so that it first lists all the items in the top level (level 1) followed by the lower levels (2, 3, 4 etc...)
There can be multiple duplicates (not just 2), so any solution will have to factor that in
Would like the duplicate(s) too be highlighted in Bold Red
If more information is needed please let me know.
Edit: More Details added below 08/05/2022
Here is the code I am working with which begins with a recursive CTE:
WITH CTERBOM AS
(
SELECT PBL.[Production BOM No_], PBL.[Version Code], PBL.[No_], PBL.[Quantity per], 1 AS LVL
FROM [DataBaseName$Production BOM Line] PBL
LEFT JOIN [DataBaseName$Production BOM Header Extra] PBHEX ON PBHEX.[No_] = PBL.[Production BOM No_]
WHERE PBL.[Production BOM No_] = '008722' AND PBHEX.[Active Version No_] = PBL.[Version Code]
UNION ALL
SELECT PBL2.[Production BOM No_], PBL2.[Version Code], PBL2.[No_], PBL2.[Quantity per], LVL + 1
FROM [DataBaseName$Production BOM Line] PBL2
INNER JOIN CTERBOM ON CTERBOM.[No_] = PBL2.[Production BOM No_]
)
SELECT
CTERBOM.[LVL] AS [Level],
CTERBOM.[No_] AS [Item No.],
CTERBOM.[Production BOM No_] AS [Production BOM No.],
CTERBOM.[Quantity per] AS [Qty. Per]
FROM CTERBOM
LEFT JOIN [DataBaseName$Production BOM Header Extra] PBHEX ON PBHEX.[No_] = CTERBOM.[Production BOM No_]
GROUP BY
CTERBOM.[LVL],
CTERBOM.[Production BOM No_],
CTERBOM.[No_],
CTERBOM.[Quantity per],
ORDER BY
CTERBOM.[LVL],
CTERBOM.[Production BOM No_],
CTERBOM.[No_]
One way to do this would be to do add a new column to the query, as duplicates = count(*) over (partition by [Item No.]) (insert your actual column name).
Then use that to conditionally highlight the Item No field in the report if the value of the duplicates column is > 1. You would do this by going to the Item No field in the report > properties > fill > fill color > press the expression button and enter something like:
=IIf(Fields!duplicates.Value > 1,"Yellow","Default")
Add this column to your final select:
-- APPROACH 1:
SELECT
CTERBOM.[LVL] AS [Level],
CTERBOM.[No_] AS [Item No.],
count(*) over (partition by CTERBOM.[No_]) as duplicates,
/* ... */
/* APPROACH 2:
if you can't use approach 1 because of other code not currently
shown in the question, you can wrap the entire select in
another select, which will always work:
*/
WITH CTERBOM AS
(
SELECT PBL.[Production BOM No_], PBL.[Version Code], PBL.[No_], PBL.[Quantity per], 1 AS LVL
FROM [DataBaseName$Production BOM Line] PBL
LEFT JOIN [DataBaseName$Production BOM Header Extra] PBHEX ON PBHEX.[No_] = PBL.[Production BOM No_]
WHERE PBL.[Production BOM No_] = '008722' AND PBHEX.[Active Version No_] = PBL.[Version Code]
UNION ALL
SELECT PBL2.[Production BOM No_], PBL2.[Version Code], PBL2.[No_], PBL2.[Quantity per], LVL + 1
FROM [DataBaseName$Production BOM Line] PBL2
INNER JOIN CTERBOM ON CTERBOM.[No_] = PBL2.[Production BOM No_]
)
select level,
[Item No.],
count(*) over (partition by [Item No.]) as duplicates,
[Production BOM No.],
[Qty. Per]
from (
SELECT
CTERBOM.[LVL] AS [Level],
CTERBOM.[No_] AS [Item No.],
CTERBOM.[Production BOM No_] AS [Production BOM No.],
CTERBOM.[Quantity per] AS [Qty. Per]
/* rest of existing query ... */
) t;

I want to convert inner join Query in SubQuery

I am using inner join in query but I want Subquery instead of join
select [Document No_] as DocumentNo,
ledger.[Posting Date] as Date,
[Sales (LCY)] as Amount,
header.[Customer Reference] as PONo
from [Uneek Clothing Company Ltd$Cust_ Ledger Entry] ledger
inner join [Uneek Clothing Company Ltd$Sales Invoice Header] header on ledger.[Entry No_]=header.[Cust_ Ledger Entry No_]
where [Customer No_] = 'DRC01'
and [Document Type]=2
and [Sales (LCY)]!=0
and ledger.[Posting Date] between '01/01/2019' and '12/31/2019'
order by [Sales (LCY)] asc offset 0 ROWS FETCH NEXT 20 ROWS ONLY
[Entry No_] is foreign key in [Uneek Clothing Company Ltd$Sales Invoice Header] with name [Cust_ Ledger Entry No_]
if you really want to drop the join and use a subquery instead,
it will look something like this.
Since you did not use an table alias for all columns, I had to assume that no other column of table in the subquery is used anywhere else. If that is not the case then this will not work
It will also only work if the subquery returns no more then 1 row, otherwise a subquery cannot be used at all
select [Document No_] as DocumentNo,
ledger.[Posting Date] as Date,
[Sales (LCY)] as Amount,
( select header.[Customer Reference]
from [Uneek Clothing Company Ltd$Sales Invoice Header] header
where ledger.[Entry No_] = header.[Cust_ Ledger Entry No_]
) as PONo
from [Uneek Clothing Company Ltd$Cust_ Ledger Entry] ledger
where [Customer No_] = 'DRC01'
and [Document Type]=2
and [Sales (LCY)]!=0
and ledger.[Posting Date] between '01/01/2019' and '12/31/2019'
order by [Sales (LCY)] asc
offset 0 ROWS FETCH NEXT 20 ROWS ONLY

Scheduled datetime conversion error (SQL)

When trying to convert a datetime field to get rid of NULL's I am getting the error that the datetime cannot be converted.
This query is populating another database where the column datatype is date.
This job runs perfectly fine when not scheduled, but results in an error during the scheduled insert job.
Any ideas?
, (SELECT
CASE
WHEN MIN([Discount Ledger].[Posting Date]) IS NOT NULL
THEN CONVERT(VARCHAR(50), MIN([Discount Ledger].[Posting Date]), 121)
ELSE '-'
END
FROM
[Wings$Discount Ledger Entry] AS "Discount Ledger"
LEFT JOIN
[Wings$Periodic Discount] AS "MixMatchHeader" ON [Discount Ledger].[Offer No_] = [MixMatchHeader].[No_]
LEFT JOIN
[Wings$Periodic Discount Line] AS "MixMatch" ON [MixMatchHeader].[No_] = [MixMatch].[Offer No_]
LEFT JOIN
[Wings$Item_Special Group Link] AS "Special Group" ON [MixMatch].[No_] = [Special Group].[Special Group Code]
LEFT JOIN
[Wings$Store Price Group] AS "Store Price Group" ON [MixMatch].[Price Group] = [Store Price Group].[Price Group Code]
WHERE
[MixMatch].[No_] = [Item Ledger].[Item No_]
AND [MixMatch].[Variant Code] = [Item Ledger].[Variant Code]
AND [Store Price Group].[Store] = [Item Ledger].[Location Code]) AS "Discount Start Date"
You can do this using ISNULL. Since you are looking for the MIN date, I will use GETDATE() as the argument/replacement value for NULL. Unless your data has future dates, then GETDATE() should function as the MAX value. Unless you want the CASE statement to evaluate the NULL values as the MIN. In that case, you can use an empty string '' or '1900-01-01' instead of GETDATE().
, (SELECT
CASE
WHEN
MIN([Discount Ledger].[Posting Date]) IS NOT NULL
THEN CONVERT(varchar(50),MIN(ISNULL([Discount Ledger].[Posting Date],GETDATE())),121)
ELSE '-'
END
FROM [Wings$Discount Ledger Entry] AS "Discount Ledger"
LEFT JOIN [Wings$Periodic Discount] AS "MixMatchHeader" ON [Discount Ledger].[Offer No_] = [MixMatchHeader].[No_]
LEFT JOIN [Wings$Periodic Discount Line] AS "MixMatch" ON [MixMatchHeader].[No_] = [MixMatch].[Offer No_]
LEFT JOIN [Wings$Item_Special Group Link] AS "Special Group" ON [MixMatch].[No_] = [Special Group].[Special Group Code]
LEFT JOIN [Wings$Store Price Group] AS "Store Price Group" ON [MixMatch].[Price Group] = [Store Price Group].[Price Group Code]
WHERE [MixMatch].[No_] = [Item Ledger].[Item No_] AND [MixMatch].[Variant Code] = [Item Ledger].[Variant Code] AND [Store Price Group].[Store] = [Item Ledger].[Location Code])
AS "Discount Start Date"

How to return top 30 customer revenue combines from service and sales table

I can pull the individual rows with this query but want to combine the two tables and show, by customer No, the top 30 customer by salesperson.
select top 30 sil.[Sell-to Customer No_]as 'Customer No.',
cus.[Name],
sil.[Responsibility Center],
sil.[Amount] as 'Total',
'SALES'
FROM [Sales Invoice Line] sil left outer join [Customer]cus
on sil.[Sell-to Customer No_] = cus.[No_]
where sil.[Amount] > 0
and sil.[Responsibility Center] != 'cis'
and sil.[Posting Date] between '10-01-13' and (current_timestamp)
group by sil.[Amount], sil.[Sell-to Customer No_], sil.[Responsibility Center], cus.[Name]
union all
select top 30 sil.[Customer No_],
cus.[Name],
sil.[Responsibility Center],
sil.[Amount] as 'Total',
'SERVICE'
FROM [Service Invoice Line] sil left outer join [Customer]cus
on sil.[Customer No_] = cus.[No_]
where sil.[Amount] > 0
and sil.[Responsibility Center] != 'cis'
and sil.[Posting Date] between '10-01-13' and (current_timestamp)
group by sil.[Amount], sil.[Customer No_], sil.[Responsibility Center], cus.[Name]
Wrap your entire query that returns 60 rows with a query to get the top 30.
select top 30 x, y, z
from (
select top 30 x, y, z from a where blah
union all
select top 30 x, y, z from b where blah
) x --here's the alias for the subquery
order by topcriteria
The order by is important so you get the proper "top" of the query.
Edit: Here's your sum example:
select top 30 sil.[Sell-to Customer No_]as 'Customer No.',
cus.[Name],
sil.[Responsibility Center],
sum(sil.[Amount]) as 'Total',
'SALES'
FROM [Sales Invoice Line] sil left outer join [Customer]cus
on sil.[Sell-to Customer No_] = cus.[No_]
where sil.[Amount] > 0
and sil.[Responsibility Center] != 'cis'
and sil.[Posting Date] between '10-01-13' and (current_timestamp)
group by sil.[Sell-to Customer No_], sil.[Responsibility Center], cus.[Name]

T-SQL - WHERE condition performance [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have variable declared like this
DECLARE #Customer_No VARCHAR(MAX)
SET #Customer_No = 'Z110073574;Z110027464;Z110229752;Z110274156;Z110170566;Z110102837;Z110074199'
The query contains condition
WHERE ((#Customer_No = '') OR ([Customer No_] IN (SELECT [No_] FROM Customer)))
If the variable #Customer_No can contains blank value (''), filtering should be skipped. In case the variable contains customers separated by semicolons, the string is parsed into table Customer and the query is filtered by values in Customer table.
The query takes 15 minutes to run. If I use just the second condition, it takes about 50 seconds.
WHERE [Customer No_] IN (SELECT [No_] FROM Customer)
I don't get it. How is this possible? Any solution? Explanation?
Thank you.
Edit: Query
SELECT DET.[Cust_ Ledger Entry No_]
, DET.[Amount]
, DET.[Entry Type]
, CLE.[Document No_]
FROM [dbo].[Company$Cust_ Ledger Entry] CLE
LEFT JOIN [dbo].[Company$Detailed Cust_ Ledg_ Entry] DET ON CLE.[Entry No_] = DET.[Cust_ Ledger Entry No_]
WHERE ((#Customer_No = '') OR (DET.[Customer No_] IN (SELECT [No_] FROM Customer)))
AND (DET.[Entry Type] = 1 OR DET.[Entry Type] = 2)
AND (CLE.[Due Date] >= #FromDueDate AND CLE.[Due Date] <= #ToDueDate)
AND CLE.[Posting Date] <= #ToDate
I think you can simply the query without loss of integrity to the following. Like Aaron said, can you post a query plan?
SELECT
DET.[Cust_ Ledger Entry No_],
DET.[Amount],
DET.[Entry Type],
CLE.[Document No_]
FROM
[dbo].[Company$Cust_ Ledger Entry] CLE
LEFT JOIN
[dbo].[Company$Detailed Cust_ Ledg_ Entry] DET
ON
CLE.[Entry No_] = DET.[Cust_ Ledger Entry No_]
WHERE
( #FAS_No = '' OR DET.[Customer No_] IN (SELECT [No_] FROM Customer) )
AND DET.[Entry Type] in (1, 2)
AND CLE.[Due Date] >= #FromDueDate
AND CLE.[Due Date] <= #ToDueDate
AND CLE.[Posting Date] <= #ToDate
It's not easy to pinpoint the exact problem without more information (table structure, # of rows, etc). However, one thing for sure is the the use of OR in TSQL reduces overall performance. If there is a way to use an AND instead of an OR than it's recommended you do so.
what you can always do it use an IF statement that check if the variable is empty. If not, you use the SELECT with the WHERE. If it is empty, you use the SELECT without the WHERE.
Another thing to check might be your indexes. That can speed things a little.
The DET in the where is killing the left so might as well join
If you pull conditions into the join then the query optimizer seems to do a better
I think this gives a the query optimizer a better chance
SELECT DET.[Cust_ Ledger Entry No_]
, DET.[Amount]
, DET.[Entry Type]
, CLE.[Document No_]
FROM [dbo].[Company$Cust_ Ledger Entry] CLE
JOIN [dbo].[Company$Detailed Cust_ Ledg_ Entry] DET
ON CLE.[Entry No_] = DET.[Cust_ Ledger Entry No_]
AND ( DET.[Entry Type] IN (1,2) )
AND ( CLE.[Due Date] >= #FromDueDate AND CLE.[Due Date] <= #ToDueDate )
AND CLE.[Posting Date] <= #ToDate
JOIN Customer
ON #Customer_No = ''
OR DET.[Customer No_] = Customer.[No_]
And try hints
I would start with INNER MERGE JOIN Customer
And please [NO_] is declared as a PK
I think you can reduce the performance by writing in
USE CTE for - (SELECT [No_] FROM Customer)
Join cte with the main table which will give you performance

Resources