|
Once you've declared the @Quarter variable or parameter, you'll run into another error:
Invalid column name 'Quarter'.
You can't reference an alias introduced in the SELECT clause within the WHERE clause of the same statement. You either have to use a sub-query, a common table expression, or duplicate the logic of the alias in the WHERE clause.
SELECT Quarter
FROM
(
SELECT CASE
WHEN InvoiceMonth IN (1,2,3) THEN 1
WHEN InvoiceMonth IN (4,5,6) THEN 2
WHEN InvoiceMonth IN (7,8,9) THEN 3
WHEN InvoiceMonth IN (10,11,12) THEN 4
END As Quarter
FROM viewSalesTracker_Model1
)
WHERE Quarter = @Quarter; Or:
WITH cteQuarters As
(
SELECT CASE
WHEN InvoiceMonth IN (1,2,3) THEN 1
WHEN InvoiceMonth IN (4,5,6) THEN 2
WHEN InvoiceMonth IN (7,8,9) THEN 3
WHEN InvoiceMonth IN (10,11,12) THEN 4
END As Quarter
FROM viewSalesTracker_Model1
)
SELECT Quarter
FROM cteQuarters
WHERE Quarter = @Quarter; Or:
SELECT CASE
WHEN InvoiceMonth IN (1,2,3) THEN 1
WHEN InvoiceMonth IN (4,5,6) THEN 2
WHEN InvoiceMonth IN (7,8,9) THEN 3
WHEN InvoiceMonth IN (10,11,12) THEN 4
END As Quarter
FROM viewSalesTracker_Model1
WHERE CASE
WHEN InvoiceMonth IN (1,2,3) THEN 1
WHEN InvoiceMonth IN (4,5,6) THEN 2
WHEN InvoiceMonth IN (7,8,9) THEN 3
WHEN InvoiceMonth IN (10,11,12) THEN 4
END = @Quarter;
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I cannot figure out why my trigger keeps inserting duplicates. Do anyone see what might might be causing it.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[update_ee_so_email]
ON [dbo].[import_new_soemailsubmission]
AFTER INSERT , UPDATE, Delete
AS
BEGIN
Declare @new_agentId as uniqueidentifier --varchar(10)
Declare @new_email as varchar(50)
Declare @agentid as varchar(10)
Select @agentid = SO.new_agentId, @new_email = new_email
FROM inserted SE join import_new_serviceorganization SO ON SE.new_agentId = SO.ID
join app_users a on a.user_name = 'SO-' + SO.new_agentid
IF @agentid is not null
Begin
INSERT INTO EE_SO_MAILING_LISTS ([PARTNER], EMAIL_ADDRESS,STATEMENT_FLAG, REFRESH_DATE)
Values(@agentid, @new_email, 'N', GetDate())
END
Else if exists (Select * from deleted)
Begin
Select @new_agentId = new_agentId, @new_email = new_email
FROM deleted
Select @agentid =new_agentId From import_new_serviceorganization Where id = @new_agentId
Delete from EE_SO_MAILING_LISTS where PARTNER = @agentid and EMAIL_ADDRESS = @new_email
End
END
|
|
|
|
|
You can't treat triggers like this. Triggers will often have multiple records in the inserted and deleted tables so you can't use variables.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
How are you suppose to do them?
|
|
|
|
|
Depends on what you were trying to do but using variables will never work when there’s more than one record in the inserted or deleted tables.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
As well as the issue of multiple affected records, your trigger is trying to handle all three DML operations (INSERT , UPDATE , and DELETE ). But the code only seems to be handling the INSERT and DELETE cases.
- For
INSERT , there will be records in the inserted virtual table, but none in the deleted virtual table; - For
DELETE , there will records in deleted , but none in inserted ; - For
UPDATE , there will be records in both;
Use the inserted and deleted Tables - SQL Server | Microsoft Docs[^]
It would almost certainly be simpler to have separate queries for each operation. Try something like this:
CREATE OR ALTER TRIGGER [dbo].[insert_ee_so_email]
ON [dbo].[import_new_soemailsubmission]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.EE_SO_MAILING_LISTS
(
[PARTNER],
EMAIL_ADDRESS,
STATEMENT_FLAG,
REFRESH_DATE
)
SELECT
SO.new_agentId,
I.new_email,
'N',
GetDate()
FROM
inserted As I
INNER JOIN dbo.import_new_serviceorganization As SO
ON SO.ID = I.new_agentId
WHERE
Exists
(
SELECT 1
FROM dbo.app_users As A
WHERE A.user_name = 'SO-' + SO.new_agentId
)
;
END
GO
CREATE OR ALTER TRIGGER [dbo].[update_ee_so_email]
ON [dbo].[import_new_soemailsubmission]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
If Updated(new_email)
BEGIN
UPDATE
L
SET
EMAIL_ADDRESS = I.new_email
FROM
dbo.import_new_serviceorganization As SO
INNER JOIN inserted As I
ON I.new_agentId = SO.ID
INNER JOIN deleted As D
ON D.new_agentId = SO.ID
INNER JOIN dbo.EE_SO_MAILING_LISTS As L
ON L.PARTNER = SO.new_agentId
And L.EMAIL_ADDRESS = D.new_email
;
END;
END
GO
CREATE OR ALTER TRIGGER [dbo].[delete_ee_so_email]
ON [dbo].[import_new_soemailsubmission]
AFTER DELETE
AS
BEGIN
SET NOCOUNT ON;
DELETE
FROM
L
FROM
dbo.EE_SO_MAILING_LISTS As L
WHERE
Exists
(
SELECT 1
FROM dbo.import_new_serviceorganization As SO
INNER JOIN deleted As D
ON D.new_agentId = SO.ID
WHERE SO.new_agentId = L.PARTNER
And D.new_email = L.EMAIL_ADDRESS
)
;
END
GO
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
IMHO you are creating a nightmare for your successor by implementing business rules in a trigger. He/she is going to ask where the hell are all these emails coming from? And will spend the next #n hours/days searching for the code that generates the emails.
When he/she does eventually think to look into triggers they will heap curses on your name. Triggers should only be used for audit purposes not business rules.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
Hi,
I need to insert all the records from an excel sheet to a sql database table and find out below through sql queries.Excel is attached for reference below
device_id device_name appanalyticssessioneventid app_name category local_time
1223593358dfa0030bfb23209fe2c93b8fe0f0ac2af363b9760e84d0ff2e926c Galaxy S9 Plus 1223593358dfa0030bfb23209fe2c93b8fe0f0ac2af363b9760e84d0ff2e926c:2018-04-20T15:15:37.139UTC:2018-04-20T10:11:14.000 -0500 Robinhood Finance 4-20-2018 10:12:53
1cab04b741fa186ddeb5145df7905eb918ad45a09638a3faac0a2c30d60c38bc Galaxy S9 1cab04b741fa186ddeb5145df7905eb918ad45a09638a3faac0a2c30d60c38bc:2018-04-20T23:53:21.784UTC:2018-04-20T18:17:56.000 -0500 KNOX Configure Productivity 4-20-2018 17:53:02
102151dd863d3ac3f70ec3ed9aa105a847ebf02574300446911d567aa9f713f4 Galaxy S9 Plus 102151dd863d3ac3f70ec3ed9aa105a847ebf02574300446911d567aa9f713f4:2018-05-15T06:29:19.679UTC:2018-05-14T21:33:41.000 -0700 YouTube Entertainment 5-14-2018 21:45:19
[edit]
Removed thousands of lines of the same text
[/edit]
a)Daily avg of app session count per device id
b)How many times on an average user login to facebook app weekly
Thanks,
Barath
modified 30-Mar-20 8:37am.
|
|
|
|
|
Are you insane!!!?
You posted thousands of line of gibberish and then expected someone else to do all the work for you?!! Come on man!!
Provide you credit card number and I'll gladly do this for you.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
1. Thank you for cleaning up your question.
2. What exactly do you want us to do? You have several different requirements. You need to break them down into tasks and do each one.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
You have just identified the groupings for your query.
a) select the fields, group by date, appID, deviceID and do a count.
b) identify the facebook appid, repeat A with a where clause filtering the appid.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
I have a survey table where people were asked up 7 question and I'm trying to figure out the best way to assign a primary key in sql. here how it looks like.
key surveyid questionid answid questions answer
ed45894 1 3 1 when was the last time you bought soda 1 week ago
ed45894 1 7 2 How many live in your house 4
ed45894 1 4 5 do you children in your house Yes
ed45894 1 2 7 do you use coupon while shopping No
fs45895 1 3 4 when was the last time you bought soda yesterday
fs45895 1 7 2 How many live in your house 1
fs45895 1 4 5 do you children in your house Yes
fs45895 1 2 7 do you use coupon while shopping No
|
|
|
|
|
You're highly unlikely to overrun an int for surveys.
"Never attribute to malice that which can be explained by stupidity."
- Hanlon's Razor
|
|
|
|
|
learning_new wrote: trying to figure out the best way to assign a primary key in sql There is only one way to do so; you find the column or columns that uniquely identify a single row in the collection.
If you are having trouble with it, you're not normalizing. Your table should be in 3NF; or in short, you want the key, the whole key, and nothing but the key. Codd's law, look it up.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Can you explain what these columns are ?
Looks like you have enough data to make a primary key, but understanding the data would lead to a suggestion.
|
|
|
|
|
Thanks David. I was able to figure out.
|
|
|
|
|
Say I have this TSQL table
create table Table (
TableId int identity(1, 1) not null,
value nvarchar(max) null,
id0 int null,
id1 int null,
id2 int null
)
and say I make a query like (getting the biggest id2 for a given id0 and id1 )
declare @arg0 int = 2
declare @arg1 int = 3
select top 1 id2
from Table
where id0 = @arg0 and id1 = @arg1
order by id2 desc
What would be the better index Index1 , or Index2 ?
create index Index1 on Table (id2) include (id0, id1)
create index index2 on Table (id0, id1, id2)
modified 5-Feb-20 20:52pm.
|
|
|
|
|
Index3. Didn't actually try it, just based it on documentation.
Super Lloyd wrote: create index index2 on Table (id0, id1, id2) Creates a composite index, based on those three columns, sorted first by id0, and within that group on id1, and within that group on id2.
Super Lloyd wrote: create index Index1 on Table (id2) include (id0, id1) Creates a index on id2, but adds the (values of) columns id0 and id1 to the index for quick access.
Super Lloyd wrote: What would be the better index Index1 , or Index2 ? You mean "faster"? Do you mean faster read, or faster write? From what I see, they'd both need to write three fields when writing, since the index needs be updated. They'd both supply the three fields from the index (without accessing the table) when reading. The bigger difference is in the first field of the index, id2 in one, id0 in the other. Both queries seem to cover the query, but the docs point to making a composite of all three fields;
Redesign nonclustered indexes with a large index key size so that only columns used for searching and lookups are key columns. Make all other columns that cover the query into nonkey columns. In this way, you will have all columns needed to cover the query, but the index key itself is small and efficient. Which field comes first in that list, is also on MSDN;
List the columns to be included in the composite index, in sort-priority order Soo.. option 2? Maybe option 3, with (id0, id1, id2); you are first looking up on the first two fields, than ordering on id2. That'd be my guess, given the example query and the docs. You could of course create a table and actually test that; MSSQLMS would give you an execution plan with timings.
Why is there an identity field? Wouldn't id0 and id1 simply be your primary key? That's what you are using to locate a unique value in the set; if you're not actively using the identity-field, then inserts would benefit from removing it. If you make id0 and id1 your primary key, then the table will have a clustered index on those fields, meaning the table is physically sorted on those fields. For large tables, that would be actually preffered;
The preferred way to build indexes on large tables is to start with the clustered index and then build any nonclustered indexes So docs are hinting that (for large sets) a clustered index is preferred and autmatically created when defining a PK; but then the ids' can't be NULL . If those ids' represent categories, you may even want to go for a filtered index.
I hope for you that someone posts an answer that simply says the first or the second, without all these details
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Mm.. you seem to recommend Index2 so I am confused by your "Index3 " on the first line...
basically this is a table that aggregate a summary from multiple data sources. id0 and id1 identify the datasource and are small number (between 1 to 9 each) and id2 is the original record id in the foreign datasource.
I am interested to speed up read query...
But.. mmm... I realize this particular query is not too important.. and querying by id2 will be used elsewhere... mmmmm.....
Thanks for your feedback and MSDN quotes though!
|
|
|
|
|
Super Lloyd wrote: Mm.. you seem to recommend Index2 so I am confused by your "Index3 " on the first line... Same as Index2, but with another order of the fields.
Super Lloyd wrote: basically this is a table that aggregate a summary from multiple data sources. id0 and id1 identify the datasource and are small number (between 1 to 9 each) and id2 is the original record id in the foreign datasource. That makes those three fields a compound primary key.
Super Lloyd wrote: Thanks for your feedback and MSDN quotes though! My pleasure, and seems they know most about Sql Server
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Index2 is the faster one because index1 will not be used at all except maybe for a full scan.
You might want to create it as;
create index index2 on Table (id0, id1, id2 DESC) But the difference is academical at best. SQL Server can scan in reverse direction after all.
|
|
|
|
|
For that query, definitely index 2.
Think of it like searching a massive address book. You're trying to find the highest house number for anyone called "John Smith".
- Index 1 sorts the addresses by house number, and includes the first and last name. You have to start at the end and scan backwards until you find an entry for "John Smith".
- Index 2 sorts the addresses by first name, then last name, then house number. You can jump straight to the end of the "John Smith" records, and see the highest house number.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The quote below is from An Introduction to Database Systems, 8th edition, C J Date.
Is that possible systems crash while transferring updates from the physical device to the database?
If yes, since transactions are the unit of recovery, those updates that are written to the database should be undone?
"It is quite possible, for instance, that the system might crash after the COMMIT has been honored but before the updates have been physically written to the database--they might still be waiting in a main-memory buffer and so lost at the time of the crash. Even if that happens, the system's restart procedure will still record those updates in the database: it is able to discover the values to be written by examining the relevant records in the log."
modified 2-Feb-20 13:48pm.
|
|
|
|
|
Not sure if I understand the question correctly, but are you looking for Rollforward? . With rollforward, when the database is recovered, all the logs are reapplied and in the end, everything that is not committed is rolled back. This guarantees a consisted situation even after crash.
If the recovery is interrupted because of a new crash, the recovery is simply started from the beginning next time.
|
|
|
|
|
Many thanks!
Sorry can you please explain this:
If the system crash after the COMMIT has been honored but just part of the updates have been physically written to the database other parts are still waiting in a main-memory buffer, then what will happen? How they know that just part of the data is written?
|
|
|
|
|