Select distinct and add one to that value - sql

I have a database with a column containing year-week in this format "202030, 202031" and so on. However the weeks are US-format and to be in Swedish format I need to add 1 to this integer.
I have this query that works but gives me the "wrong week":
Select distinct date_week FROM table Order by date_week desc
I have tried this without success:
Select distinct date_week +1 FROM table Order by date_week desc
How do I add +1 to the volumes in that date-week column?

Does this do what you want?
select date_week + 1
from table
group by date_week
order by date_week desc;
You don't specify the issue with your query, but it might simply be the select distinct.

Related

using date of datetime in group by and order by in single SELECT versus using subquery

I (suddenly?) have trouble getting this very simple query to work on Google BigQuery without using a subquery and not sure why.
The data contains a datetime column and I just want to check up on the number of rows per day.
However, it keeps complaining I'm using the datetime column 'which is neither grouped or aggregated'.
SELECT date(datetime_col) as row_date, count(*) as count
FROM table1
GROUP BY date(datetime_col)
ORDER BY count DESC
Without the ORDER BY it works just fine. When I add the ORDER BY it suddenly complains the
'SELECT list expression references column 'datetime_col' which is
neither grouped nor aggregated'
If I remove the count and group by and order by on the date then it does work.
Now if I use a subquery to do the date casting in there it does work:
SELECT row_date, count(row_date) as count FROM
(SELECT date(datetime_col) as row_date FROM table1)
GROUP BY row_date
ORDER BY count DESC
So I'm wondering what is going on why the first single select query is not working and if that can be fixed without using the subquery?
Try putting row_date into GROUP BY:
SELECT date(datetime_col) as row_date, count(*) as count
FROM table1
GROUP BY row_date
ORDER BY count DESC

how to get latest date column records when result should be filtered with unique column name in sql?

I have table as below:
I want write a sql query to get output as below:
the query should select all the records from the table but, when multiple records have same Id column value then it should take only one record having latest Date.
E.g., Here Rudolf id 1211 is present three times in input---in output only one Rudolf record having date 06-12-2010 is selected. same thing with James.
I tried to write a query but it was not succssful. So, please help me to form a query string in sql.
Thanks in advance
You can partition your data over Date Desc and get the first row of each partition
SELECT A.Id, A.Name, A.Place, A.Date FROM (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Date DESC) AS rn
FROM [Table]
) A WHERE A.rn = 1
you can use WITH TIES
select top 1 PERCENT WITH TIES * from t
order by (row_number() over(partition by id order by date desc))
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=280b7412b5c0c04c208f2914b44c7ce3
As i can see from your example, duplicate rows differ only in Date. If it's a case, then simple GROUP BY with MAX aggregate function will do the job for you.
SELECT Id, Name, Place, MAX(Date)
FROM [TABLE_NAME]
GROUP BY Id, Name, Place
Here is working example: http://sqlfiddle.com/#!18/7025e/2

Some two columns using alias in order by

I have this query:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by "visits", "visitors"
It works.
If I change to this
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (("visits") + ("visitors"))
I get
column "visits" does not exist
If I change to
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by count(1) + count(distinct visitor_id)
it works again.
Why does it work for example 1 and 3, but not for example 2? Is there any way to order by the sum of two column using their aliases?
The alternatives I could think of:
Create an outer select and order it, but that would create extra code and I would like to avoid that
Recalculate the values in the order by statement. But that would make the query more complex and maybe I would lose performance due to recalculating stuff.
PS: This query is a toy-query. The real one is much more complicated. I would like to reuse the value calculated in the select statement in the order by, but all summed up together.
Expression evaluation order is not defined. If your visits + visitors expression is evaluated before aliases you will get the error shown here above.
Instead of using the alias try using the actual column also try change the type to varchar or nvarchar, and by that I mean the following:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (CAST(count(1) AS VARCHAR) + CAST(count(distinct visitor_id) AS VARCHAR))

Selecting and modifying a field in SQL

Let's say I have a table with name and birthday fields. I can use this SQL to return a table of items sharing the same birthday (e.g. 4 people have the birthday 4/8/1995):
SELECT DISTINCT "Birthday", COUNT("Birthday") as "FieldCount"
FROM "test_main" Group BY "Birthday" Order By "FieldCount" DESC
But how can I modify the value that I select to ignore the year, e.g. get a count of birthdays by month, for example, Jan: 42 names, Feb: 28 names, etc
Thanks
SELECT month(Birthday), COUNT(Birthday)
FROM test_main
Group BY month(Birthday)
Order By COUNT(Birthday) DESC
One way is to use built in functions to extract the year and month:
SELECT month(birthday), count(*) as FieldCount
FROM test_main
Group BY month(birthday)
Order By FieldCount DESC;
Notes:
There is no need for the distinct with a group by.
You do not need to surround everything with double quotes.
COUNT(*) should be find for what you want.

SQL How to remove duplicates within select query?

I have a table which looks like that:
As You see, there are some date duplicates, so how to select only one row for each date in that table?
the column 'id_from_other_table' is from INNER JOIN with the table above
There are multiple rows with the same date, but the time is different. Therefore, DISTINCT start_date will not work. What you need is: cast the start_date to a DATE (so the TIME part is gone), and then do a DISTINCT:
SELECT DISTINCT CAST(start_date AS DATE) FROM table;
Depending on what database you use, the type name for DATE is different.
Do you need any other information except the date? If not:
SELECT DISTINCT start_date FROM table;
You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.
Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?
In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.
SELECT MAX(owner_name),
--floored to the second
dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
From MyTable
GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')
Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table
If you want to select any random single row for particular day, then
SELECT * FROM table_name GROUP BY DAY(start_date)
If you want to select single entry for each user per day, then
SELECT * FROM table_name GROUP BY DAY(start_date),owner_name
here is the solution for your query returning only one row for each date in that table
here in the solution 'tony' will occur twice as two different start dates are there for it
SELECT * FROM
(
SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC ) RNM
FROM TABLE T1
)
WHERE RNM=1
You have to convert the "DateTime" to a "Date". Then you can easier select just one for the given date no matter the time for that date.