Select top 50 rows in sql server - sql

I have below T-SQL code used in SQL Server 2014.
This code produces 1000s of rows. But i need only top 50 rows (from Supplier Column) from this.
In the below code, if I use SELECT Top 50 s.[CusNo] Supplier then I am not getting desired results.
What changes needs to be done in the below code in order to get only Top 50 rows (of Supplier column) with out any change in the existing result.
SELECT s.[CusNo] Supplier,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConcessionNo] Concession,
RTRIM(CAST(s.[ConcessionName] AS VARCHAR(50)) ) AS ConcessionName,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELLINC else 0 end) ActualSales,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) -1 /* On 14/Feb/2021 modify +6 to -1 */) and convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end) LastYrVariance,
(sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5) then s.SELLINC else 0 end))-
(sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) -1 /* On 14/Feb/2021 modify +6 to -1 */) and convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */) then s.SELLINC else 0 end)) LastYrVariancePounds,
(IsNull(sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELLINC else 0 end)-sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) -1 /* On 14/Feb/2021 modify +6 to -1 */) and convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end),0)/NullIf(sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) -1 /* On 14/Feb/2021 modify +6 to -1 */) and convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end),0))*100 LastYrVariancePercentage,
sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(GetDate()) = 1 THEN CONVERT(VARCHAR(4), GetDate(), 112) - 1 ELSE CONVERT(VARCHAR(4), GetDate(), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
Convert(date, dateadd(wk, datediff(wk, 0, GETDATE()) - 1, 0) + 5)
then s.SELLINC else 0 end) YrToDateActual,
sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(DATEADD(year,-1,GetDate())) = 1 THEN CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) - 1 ELSE CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end) LastYrToDateActual,
(sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(GetDate()) = 1 THEN CONVERT(VARCHAR(4), GetDate(), 112) - 1 ELSE CONVERT(VARCHAR(4), GetDate(), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
Convert(date, dateadd(wk, datediff(wk, 0, GETDATE()) - 1, 0) + 5)
then s.SELLINC else 0 end))
-
(sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(DATEADD(year,-1,GetDate())) = 1 THEN CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) - 1 ELSE CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end)) YrToDateVariancePounds,
((IsNull
(
(sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(GetDate()) = 1 THEN CONVERT(VARCHAR(4), GetDate(), 112) - 1 ELSE CONVERT(VARCHAR(4), GetDate(), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
Convert(date, dateadd(wk, datediff(wk, 0, GETDATE()) - 1, 0) + 5)
then s.SELLINC else 0 end))
-
(sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(DATEADD(year,-1,GetDate())) = 1 THEN CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) - 1 ELSE CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end))
,0)
)
/
(NullIf
(
sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(DATEADD(year,-1,GetDate())) = 1 THEN CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) - 1 ELSE CONVERT(VARCHAR(4), DATEADD(year,-1,GetDate()), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
convert(date,dateadd(wk, datediff(wk, 0, dateadd(YEAR, - 1, getdate())) - 1, 0) + 5 /* On 14/Feb/2021 modify +12 to +5 */)
then s.SELLINC else 0 end)
,0)))*100 LastYrToDateVariancePercentage
FROM [dbo].[CustomerReports] s
WHERE s.BRN = 1 or s.BRN = 2 or s.BRN = 3 or s.BRN = 4 or s.BRN = 5 or s.SELLINC is null or s.SELLINC = '0'
GROUP BY s.[CusNo], s.[Customer], s.ConcessionNo, s.ConcessionName
order by YrToDateActual desc
When I run this Query In SSRS I get below results (Which is Correct). But displays all the data.
if I use SELECT Top 50 s.[CusNo] Supplier (Rest of the code is same) then I am getting the below,
So please see the highlighted section in both the images. When I add Top 50 in SQL code then few rows (in 3rd column ) which were present in 1st image is not present in 2nd image.

Try this:
With cte as (**your long query goes here**)
Select Top(50) * From cte

The sort order in your query is by YrToDateActual desc, so the TOP 50 is giving you the highest 50 YrToDateActual amounts. Your SSRS report is grouping by Supplier number and name, but doesn't look to be sorting by either of these columns, so I'm guessing that the order of these suppliers is somewhat random in the SSRS output. In this case I don't think you're ever going to be able to get the first 50 rows of your original SSRS output. The best you could do would be to also sort your SSRS output (e.g. by Supplier number) and then add this sort into your query (order by Supplier, YrToDateActual desc). Adding the TOP 50 into your query would cut off your new sorted SSRS output after the first 50 results.

What do you want to see in the report? Do you want to see the top 50 suppliers based on their total value (e.g. Actual £ Total) and then all the Concessions (as per your first screenshot) ?
If so, you will need to rank the suppliers by their total and select any that are rank 50 or below.
Here's a very simplified example that might help. In this I've used SUM() OVER() rather than using GROUP BY but this means you might want to change the SELECT to SELECT DISTINCT depending on you needs as you will get lots of duplicate rows. Obviously it's not got your lengthy case statements in but you should be able to adapt it easily.
SELECT * FROM
(
SELECT
x.*
, DENSE_RANK() OVER(ORDER BY SupplierTotal DESC) as SupplierRank
, DENSE_RANK() OVER(PARTITION BY SupplierID ORDER BY ConcessionTotal DESC) as ConcessionRank
FROM
( SELECT DISTINCT
SupplierID, ConcessionID, MyOtherRequiredColumns,
SUM(myValue) OVER(PARTITION BY SupplierID) AS SupplierTotal,
SUM(myValue) OVER(PARTITION BY SupplierID, ConcessionID) AS ConcessionTotal
FROM MyTable
) x
) z
WHERE SupplierRank <= 50
This will also rank the concessions within supplier which might be useful..
You will also have to change you report where you have summed the values up (e.g. 99,389 in Actual £ column). Instead of summing the rows below, change the expression to be =FIRST(Fields!SupplierTotal.Value)

Related

SQL to exclude NULL or value 0

I have below SQL code,
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50))) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50))) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2
AND s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
When I execute the above query, I am getting all the values (including 0 values) in ActualSales column.
How to remove the rows which as value 0 please?
Use having clause
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 and s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
having sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end)<>0
OR you can use subquery
select * from
(
SELECT s.[CusNo] Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELL else 0 end) ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 and s.SELL <> 0
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN
)A where ActualSales<>0
I think you might get what you want by moving the case condition to the where clause:
SELECT s.[CusNo] as Supp,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConNo] as Con,
RTRIM(CAST(s.[ConN] AS VARCHAR(50)) ) AS ConN,
SUM(s.SELL) as ActualSales
FROM [dbo].[Reports] s
WHERE s.BOX = 2 AND s.SELL <> 0 AND
s.Date BETWEEN convert(date, dateadd(wk, datediff(week, 0, getdate()) - 1, 0) - 1) and
convert(date,dateadd(wk, datediff(week, 0, getdate()) - 1, 0) + 5)
GROUP BY s.[CusNo], s.[Customer], s.ConNo, s.ConN;
It is possibly that ActualSales could still be 0 (if Sales could be negative. In that case, you would want a HAVING clause: HAVING SUM(Sales) <> 0.
Because this approach filters before aggregation, it might also benefit performance.

How to return just the yyyy-mm-dd from the following SQL queries [duplicate]

This question already has answers here:
How to get a date in YYYY-MM-DD format from a TSQL datetime field?
(25 answers)
Closed 4 years ago.
Below are the queries I created. Query #1 returns 2018-07-06 00:00:00.000 and query #2 returns 2018-07-31 23:59:59.997.
I can't figure out how to modify the queries so that they'll return the result in the yyyy-mm-dd format. Please advice.
Query #1 - get fifth business day of the month
SELECT
FifthWeekDay = DATEADD(dd, CASE
WHEN DATEDIFF(dd, -1, ca.FirstOfMonth) % 7 > 1 -- -1 is a Sunday
THEN 7
ELSE 6 - DATEDIFF(dd, -1, ca.FirstOfMonth) % 7 -- -1 is a Sunday
END, ca.FirstOfMonth - 1)
FROM
(SELECT
DATEADD(mm, (SELECT DATEPART(YEAR, GETDATE())) * 12 - 22801 +
(SELECT DATEPART(M, GETDATE())), 0)) ca(FirstOfMonth)
Query #2 - get last business day of the month
SELECT
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
- CASE DATENAME(dw, DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)))
WHEN 'SUNDAY' THEN 2
WHEN 'SATURDAY' THEN 1
ELSE 0
END AS LastBusinessCurrentMonth
You can subquery the results you already have and add a cast( as date):
SELECT CAST(LastBusinessCurrentMonth AS DATE) AS LastBusinessCurrentMonth FROM(
SELECT
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
- CASE DATENAME(dw, DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)))
WHEN 'SUNDAY' THEN 2
WHEN 'SATURDAY' THEN 1
ELSE 0
END AS LastBusinessCurrentMonth) AS X
SELECT CAST(FIFTHWEEKDAY AS DATE) AS FIFTHWEEKDAY FROM(
SELECT
FifthWeekDay = DATEADD(dd, CASE
WHEN DATEDIFF(dd, -1, ca.FirstOfMonth) % 7 > 1 -- -1 is a Sunday
THEN 7
ELSE 6 - DATEDIFF(dd, -1, ca.FirstOfMonth) % 7 -- -1 is a Sunday
END, ca.FirstOfMonth - 1)
FROM
(SELECT
DATEADD(mm, (SELECT DATEPART(YEAR, GETDATE())) * 12 - 22801 +
(SELECT DATEPART(M, GETDATE())), 0)) ca(FirstOfMonth)) AS X
Or you could declare a variable as Date and set the results of your queries to that variable :
DECLARE #DATEVAR DATE
SET #DATEVAR =(
SELECT
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
- CASE DATENAME(dw, DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)))
WHEN 'SUNDAY' THEN 2
WHEN 'SATURDAY' THEN 1
ELSE 0
END AS LastBusinessCurrentMonth)
SELECT #DATEVAR AS LastBusinessCurrentMonth
SET #DATEVAR = (SELECT
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
- CASE DATENAME(dw, DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)))
WHEN 'SUNDAY' THEN 2
WHEN 'SATURDAY' THEN 1
ELSE 0
END AS LastBusinessCurrentMonth)
SELECT #DATEVAR AS LastBusinessCurrentMonth

removing nulls in case statement

I am trying to return the current Monday along with previous monday's data. I want to roll up my nulls or 0000 to have one record return.
select
da.Customer,
sum(case
when DAteadd(wk, datediff(wk, 0, Getdate()), 1) = d.FullDate
then (da.[USD - Balance])
else 0
end) as MondayofCurrentWeek,
sum(case
when DAteadd(wk, datediff(wk, 0, Getdate() - 7), 1) = d.FullDate
then (da.[USD - Balance])
else 0
end) as PreviousMonday
from
Dataset_DemandArchive da
inner join
Dimdate d on d.DateNameUS = da.CREDAT_0
where
da.CREDAT_0 in (dateadd(wk, datediff(wk, 0, Getdate()), 1),
dateadd(wk, datediff(wk, 0, Getdate() - 7), 1))
group by
Customer, FullDate
order by
1
Why not just use window functions?
select da.*
from (select da.Customer, d.FullDate,
sum(da.[USD - Balance]) as MondayCurrentWeek
lag(sum(da.[USD - Balance]), 7) over (partition by da.Customer order by d.FullDate)
from Dataset_DemandArchive da join
Dimdate d
on d.DateNameUS = da.CREDAT_0
group by Customer, FullDate
) da
where da.CREDAT_0 = dateadd(week, datediff(week, 0, Getdate()), 1)

SSRS - Row visibility expression

I am using SSRS 2014.
I want to display only first 50 rows. What will be the expression for this please.
I used top n functionality it doesn't work. So I thought to take another route to achieve the result via expression.
Below image with out adding 'top n'. In the below image I wanted to display only first 50 rows in Supplier column
Below image with adding 'top n'. Then results are changed. Few rows in Concession column are missing.
SQL code is,
SELECT s.[CusNo] Supplier,
RTRIM(CAST(s.[Customer] AS VARCHAR(50)) ) AS Name,
s.[ConcessionNo] Concession,
RTRIM(CAST(s.[ConcessionName] AS VARCHAR(50)) ) AS ConcessionName,
sum(case when s.Date between convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) - 1) and convert(date,dateadd(wk, datediff(wk, 0, getdate()) - 1, 0) + 5)
then s.SELLINC else 0 end) ActualSales,
sum(case when s.Date
BETWEEN
convert(varchar(10), DATEADD(day, DATEDIFF(day, '19000107', DATEADD(month, DATEDIFF(MONTH, 0, CONVERT(date, CONVERT(VARCHAR(4), (CASE WHEN MONTH(GetDate()) = 1 THEN CONVERT(VARCHAR(4), GetDate(), 112) - 1 ELSE CONVERT(VARCHAR(4), GetDate(), 112) END), 112) + '0101')), 30)) / 7 * 7, '19000107'), 120)
AND
Convert(date, dateadd(wk, datediff(wk, 0, GETDATE()) - 1, 0) + 5)
then s.SELLINC else 0 end) YrToDateActual
FROM [dbo].[CustomerReports] s
WHERE s.BRN = 1 or s.BRN = 2 or s.BRN = 3 or s.BRN = 4 or s.BRN = 5 or s.SELLINC is null or s.SELLINC = '0'
GROUP BY s.[CusNo], s.[Customer], s.ConcessionNo, s.ConcessionName
order by YrToDateActual desc
Any help please?
If you want the first 50 suppliers, you should be able to use the following expression in the row visibility property:
=RunningValue(Fields!Supplier.Value, CountDistinct,"YourDataset") > 50
The report should perform better if you put this expression as a filter on the group instead of a row visibility expression, but at the moment I can't test to confirm whether this expression would be allowed there.
Modify your ORDER BY clause to:
ORDER BY s.[CusNo], YrToDateActual desc

SQL Server correct way to account for the weekend

I have a few sql statements where I manually enter the date everyday then execute.
I would like to automate the date part. But weekends are giving me trouble. I use excel to run the reports as it is then saved and another member of staff does a mailshot.
This is my test example:
if (datename(dw, getdate()) = 'Friday') BEGIN
select convert(varchar, dateadd(day, 7, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103)
+ ',' + convert(varchar, dateadd(day, 9, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103) AS [Date] END
ELSE BEGIN select convert(varchar, dateadd(day, 7, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103) as [Date] END;
But how would I put this into a sql where statement?
for example
select * from table where (date = )
where Date equals 7 days in advance unless It's Friday when we have to account for the weekend so we want 7,8 and 9 days in advance?
select * from table where date = (case
when datename(dw, getdate()) = 'Friday' then
convert(varchar, dateadd(day, 7, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103)
+ ',' + convert(varchar, dateadd(day, 9, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103)
else
convert(varchar, dateadd(day, 7, DATEADD(dd, 0, DATEDIFF(dd, 0,getdate()))), 103)
end)