I have a table with no Primary Key columns. First column is of type DATETIME named as DateTime, the rest are of type NVARCHAR(16). Values in the column AlarmStatus can be either '0' or '1'.
As such, my table may have multiple rows with the same DateTime and different AlarmStatus values. I neeed a way to delete ALL the rows with the same DateTime ONLY IF no one of them has a '1' in AlarmStatus column.
DELETE
FROM yourTable
WHERE DateTime IN
(
SELECT DateTime
FROM yourTable
GROUP BY DateTime
HAVING SUM(CASE WHEN AlarmStatus = '1' THEN 1 ELSE 0 END) = 0
)
This can be done with a correlated subquery: You want to delete rows for which no row with the same DateTime value and a set AlarmStatus exists:
DELETE FROM MyTable
WHERE NOT EXISTS (SELECT *
FROM MyTable AS T2
WHERE T2.DateTime = MyTable.DateTime
AND T2.AlarmStatus = '1');
Alternatively, get a list of all timestamps with the status you want to keep, and check that the row to be deleted does not have one of those:
DELETE FROM MyTable
WHERE DateTime NOT IN (SELECT DateTime
FROM MyTable
WHERE AlarmStatus = '1');
Related
I'm doing a query to return the number of count records for a certain date.
The problem is when I use the GroupBy by a certain day, If the date have no records then the date for that day will not be shown in the output.
How can I achieve that?
I'm doing something like:
SELECT COUNT(History.Id)
FROM History
INNER JOIN User ON User.Id = History.UserId
WHERE (#StartDate = #NullDate OR History.CreatedOnDate >= #StartDate)
AND (#EndDate = #NullDate OR History.CreatedOnDate <= #EndDate)
GROUP BY History.CreatedOnDat
Example
01-08, 3 records
02-08, 2 records
04-08, 5 records
I need to have 03-08 with 0 records.
Create a temp table with one day per row:
Declare #StartDate datetime = '2016-08-01'
Declare #EndDate datetime = '2016-08-31'
declare #temp table
(
oneday datetime
);
WHILE #StartDate <= #EndDate
begin
INSERT INTO #temp VALUES (#StartDate);
SET #StartDate = Dateadd(Day,1, #StartDate);
end
select * from #temp
Then, simply join your query with this temp table.
How to take first value and last value of a column with group by on a particuar column?
For eg:i need first_value and last_value of case_owner column based on group by og case id.
For first value:
select case_owner as case_owner_first_value
from
table
qualify row_number() over (partition by case_id order by case_id) = 1
For last value:
select case_owner as case_owner_last_value
from
table
qualify row_number() over (partition by case_id order by case_id desc ) = 1
Please note, while combining the FIRST_VALUE with ORDER BY clause, you may need to add rows between.
Example:
CREATE VOLATILE TABLE test_fv (id INTEGER,seq SMALLINT) ON COMMIT PRESERVE ROWS;
INSERT INTO test_fv VALUES (NULL,1);
INSERT INTO test_fv VALUES (2,2);
INSERT INTO test_fv VALUES (3,3);
INSERT INTO test_fv VALUES (4,4);
INSERT INTO test_fv VALUES (5,5);
SELECT seq, FIRST_VALUE(id ignore NULLS) OVER (ORDER BY seq ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM test_fv;
This wont work:
SELECT seq, FIRST_VALUE(id ignore NULLS) OVER (ORDER BY seq ASC) FROM test_fv;
Example:
It does not work.
UPDATE column_name SET rownum FROM table_name
This work!
UPDATE table_name SET column_name = rownum;
This works but the update is performed incorrectly
SELECT * FROM table_name ORDER BY column_name;
UPDATE table_name SET column_name = rownum;
I wish the following update behavior:
Note:'rownum ' It is not a physical column of the table
/*
pc_comentario = tableName
cod_comentario = columnName (Reference column for sorting)
dtc_andamento = columnDay (Reference column to update the "columnName" according to the order of this column)
*/
rownum | columnName | columnDay
1 1 day 1
2 5 day 5
3 7 day 2
After change with update
rownum | columnName (Update this column) | columnDay (sort by this column)
1 1 day 1
2 2 day 2
3 3 day 5
ALMOST DONE! this column 'cod_comentario_1 "which was materialized in RAM is correct. I need this column" cod_comentario_1 "that does not exist in the table is acknowledged in the consultations with java.
SELECT cod_comentario, dtc_andamento, cod_processo ,
ROW_NUMBER()
OVER (PARTITION BY cod_processo
ORDER BY dtc_andamento) cod_comentario_1
FROM pc_comentario
upadate do not work this way:
UPDATE (
SELECT cod_processo
ROW_NUMBER()
OVER (PARTITION BY cod_processo
ORDER BY dtc_andamento)cod_comentario_1
FROM pc_comentario
) SET cod_comentario_1)
order by Seq
I must enter the values of this consultation in a new column that I created
SELECT
ROW_NUMBER()
OVER (PARTITION BY cod_processo
ORDER BY dtc_andamento DESC)
FROM pc_comentario
Try:
UPDATE table_name
SET column_name = rownum
Shouldn't it be like below rather; I believe UPDATE statement has no FROM clause
UPDATE table_name SET column_name = rownum;
Again, it will work only if rownum is an existing column in your table. If you are trying to use Oracle rownum instead then consider using row_number() function rather
update table_name set column_name =
select rn from ( select column_name, row_number() over (order by column_name) rn
from table_name ) xx;
As you state yourself, rownum is a virtual column. It assigns a sequential value to each row of a particular result set. Which means that the row number of a row could be completely different in the result set of a different query.
If you really want to show the row number as part of the result set, specify it as you would any column:
select rownum as columnName, columnDay
from table
order by ...;
ALTER PROCEDURE [dbo].[K_FS_InsertMrpDetails]
#date datetime,
#feedtype varchar(50),
#rateperkg float,
#rateper50kg float,
#updatedby varchar(50)
AS
BEGIN
INSERT INTO K_FS_FeedMrpDetails([date], feedtype, rateperkg, rateper50kg, updatedby, updatedon)
VALUES(#date, #feedtype, #rateperkg, #rateper50kg, #updatedby, getdate())
SELECT '1' AS status
END
With this query we insert 9 rows at a time but what I want is in one same date do not insert again different details. How can I please help me.
Add a unique constraint on the column [date]. That will prevent you from adding more than one row with the same [date] value.
Update:
To allow 9 rows for each date you can add a computed column D that removes the time part and you need to add a column that will hold the values 1 to 9 R. Use a check constraint on R to only allow 1-9. Finally you create a unique constraint on (R, D).
Sample table definition:
create table T
(
ID int identity primary key,
DT datetime not null,
R tinyint check (R in (1,2,3,4,5,6,7,8,9)) not null,
D as dateadd(day, datediff(day, 0, DT), 0),
constraint ux_RD unique (R,D)
)
Try with this:
insert into T(DT, R) values(getdate(), 1)
insert into T(DT, R) values(getdate(), 2)
insert into T(DT, R) values(getdate(), 1)
First and second insert works fine, the third raises a unique constraint exception.
I have a SQLite table as
CREATE TABLE T(
CategoryCode NVARCHAR(64) NOT NULL,
DateTime DateTime NOT NULL,
ItemCode NVARCHAR(64) NOT NULL,
ItemName NVARCHAR(64) NOT NULL,
ItemValue NUMERIC(28, 4) NOT NULL
)
The question is how to optimize indexes for the following query:
SELECT
CategoryCode
,ItemCode
,ItemName
,SUM(ItemValue) as TotalValue
FROM T
WHERE CategoryCode = 'Code1'
AND DateTime < '2012-01-04 00:00:00'
GROUP BY ItemCode
Thank you!
For the exact query, you will need an index on T(CategoryCode, DateTime) or T(DateTime, CategoryCode), depending on which column is more selective than the other.
However, it is unwise to create an index for a single query without a more holistic view on all access to the table.
e.g. You may find, for example, that if most data in the table has CategoryCode = 'Code1' then the index should only be created on the DateTime column.