I have a table name #Table1(See the attachment) I want following out put (See the attachment)
#Raging Bull's answer is correct. Here is version using PIVOT
SELECT FormatType, [True], [False], [Blank], [True] + [False] + [Blank] AS Total
FROM
(
SELECT FormatType, Result
FROM Table1
) AS SourceTable
PIVOT
(
COUNT(Result)
FOR Result IN ([True], [False], [Blank])
) AS PivotTable
It produces the exact same result.
See result in SQL Fiddle
Try this:
SELECT FormatType,
ISNULL(COUNT(CASE WHEN Result='True' THEN '1' END),0) AS [True],
ISNULL(COUNT(CASE WHEN Result='False' THEN '1' END),0) AS [False],
ISNULL(COUNT(CASE WHEN Result='Blank' THEN '1' END),0) AS [Blank],
ISNULL(COUNT(1),0) AS [Total]
FROM Table1
GROUP BY FormatType
ORDER BY FormatType DESC
Explanation:
This query will select the FormatType along the count of each cases and the total. ISNULL is used for replacing NULL values with 0 (in case of FALSE in ASP).
Result:
FORMATTYPE TRUE FALSE BLANK TOTAL
PSP 1 2 1 4
ASP 1 0 2 3
See result in SQL Fiddle.
Related
I want to write a query that selects rows by condition, but if there is no response for that condition, the code should select the same columns, but without the condition.
What the right way to do this? Thanks!
This is my example - select this:
select top 1 *
from tbl
where isActive = 1
but if there is no response, select this instead:
select top 1 *
from tbl
Note that the query is big and complex, so I prefer not to select one and then select the second one, if the first one is null. Also because I have a union after this and it throws an error with this syntax.
Assuming your query is a select top x ... query I would simply use the order by as suggested by Peter's answer. Assuming it's not involving top x, since you wrote your actual query is big and complicated, you can use a common table expression.
The idea is that you encapsulate the big and complex query inside the cte, but instead of writing the where clause to filter out records, you use a case expression to return 1 or 0 if the condition is true or false for each record.
Then you select from that cte where either the case expression results with 1 or there are no records in the cte where the case expression results with 1.
Create and populate sample table (Please save us this step in your future questions)
DECLARE #T AS TABLE
(
Id int identity(1,1),
IsActive bit
)
INSERT INTO #T VALUES
(1),(1),(NULL),(1),(1),(NULL),
(1),(1),(NULL),(1),(1),(NULL),
(1),(1),(NULL),(1),(1),(NULL),
(1),(1),(NULL),(1),(1),(NULL)
The common table expression:
;WITH CTE AS
(
SELECT Id, IsActive,
CASE WHEN IsActive = 1 THEN 1
ELSE 0
END As FoundRecords
FROM #T
)
The query:
SELECT Id, IsActive
FROM CTE
WHERE FoundRecords = 1
OR NOT EXISTS
(
SELECT 1
FROM CTE
WHERE FoundRecords = 1
)
Results:
Id IsActive
1 True
2 True
4 True
5 True
7 True
8 True
10 True
11 True
13 True
14 True
16 True
17 True
19 True
20 True
22 True
23 True
You can see a live demo on rextester
The simplest way is to not use where isActive = 1 but instead order by isActive in descending order:
select top 1 *
from tbl
order by isActive desc
You might even want to consider adding additional ordering fields (e.g. id, name, date), because without that the resulting item could be unpredictable.
You can use the IF-Else condition, right?
DECLARE #result INT
SET #result = CONVERT(INT, (SELECT COUNT(*) FROM tbl WHERE isActive = 1))
IF (#result > 0)
BEGIN
select top 1 * from tbl where isActive = 1;
END
ELSE
BEGIN
select top 1 * from tbl;
END
How can I group by 1 in SQL Server?
I have alot of SQL sum from Oracle need change to SQL Server. In sum column oracle they has been group by 1. But in Sql Server group by 1 false.
For example
Create table MyTable(
PRICE int
)
go;
select SUM(PRICE) as Total
from MyTable
Result return 1 row null.
In Oracle they have been group by 1 like this:
select SUM(PRICE) as Total
from MyTable
group by 1
Return no row.
How can I do it in Sql Server?
Group by 1 is not supported in SQL Server but you can put the same code like this:
select SUM(PRICE) as Total
from MyTable
having count(PRICE) > 0
In Sql Server <= 2012, As fa as i known . It not support GROUP by 1. But you can try sql like this will is the same.
--- Create 1 table example
CREATE TABLE table_name (
column1 int
);
--- Return 1 row if data is null:
select sum(column1) as total
from table_name
--- Return 0 row if data null <=> Oracle group by 1
select sum(column1) as total
from(
select column1, 1 as GroupBy from table_name
) a
group by GroupBy
The correct syntax for GROUP BY is
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
Condition(WHERE) is optional.
Not sure if the title is phrased correctly here...
But in any case, for simplicity's sake, I have a table with three fields like below:
USER_ID Number_Of_Apples Number_Of_Pears
ABC1 1 NULL
ABC2 1 NULL
ABC3 NULL 5
ABC4 1 12
I want to know if there's a way to do a 'distinct' query of sorts that will give me the different levels of data per field. So in the example above, I want to see something like:
USER_ID Number_OF_Apples Number_OF_Pears
4 2 3
2 is returned for Number_Of_Apples b/c we only see 2 possible values in our dataset.
I'm wondering if there's an elegant way of doing this if you had 100 fields or more?
Similar to your other question you can count distinct with a coalesce to make sure you count the nulls:
SELECT COUNT(DISTINCT(COALESCE([USER_ID], 'nullitem'))) [USER_ID],
COUNT(DISTINCT(COALESCE([Number_Of_Apples], 'nullitem'))) [Number_Of_Apples],
COUNT(DISTINCT(COALESCE([Number_Of_Pears], 'nullitem'))) [Number_Of_Pears]
FROM mytable
Just add whatever items you need.
Try this:
SELECT (SELECT COUNT(DISTINCT USER_ID)
FROM mytable) AS USER_ID,
(SELECT COUNT(DISTINCT CASE
WHEN Number_Of_Apples IS NULL THEN -1
ELSE Number_Of_Apples
END)
FROM mytable) AS Number_Of_Apples ,
(SELECT COUNT(DISTINCT CASE
WHEN Number_Of_Pears IS NULL THEN -1
ELSE Number_Of_Pears
END) AS Number_Of_Pears
FROM mytable) AS Number_Of_Pears
The above query uses a CASE expression so as to handle NULL values for Number_Of_Apples and Number_Of_Pears columns. I've made the assumption that -1 is not a possible value for these two columns.
Demo here
I have the following table:
Items:
ID Type StockExists
01 Cellphone T
02 Cellphone F
03 Apparrel T
I want to count the number of items with existing stocks, i.e., the number of rows with StockExists='T'. I was performing the query as;
Select count(StockExists)
From [Items] where StockExists='T'
but it is always returning 1. What is the right way to do it?
Edit:
Also, how to perform another such Count operation and add them together in one row, for example,
Select count(StockExists)
From [Items] where StockExists='T'` and `Select count(Type)
From [Items] where Type='Cellphone'` ?
SELECT
COUNT(*) As ExistCount
FROM
dbo.Items
WHERE
StockExists='T'
So your query should work.
Result:
EXISTCOUNT
2
Demo
Update
How to perform another such Count operation and add them together in
one row, for example, Select count(StockExists) From [Items] where
StockExists='T' and Select count(Type) From [Items] where
Type='Cellphone' ?
You can use SUM with CASE:
SELECT
ExistCount = SUM(CASE WHEN StockExists='T' THEN 1 ELSE 0 END) ,
CellphoneCount = SUM(CASE WHEN Type='Cellphone' THEN 1 ELSE 0 END)
FROM
dbo.Items
Result:
EXISTCOUNT CELLPHONECOUNT
2 2
Demo
Select Sum(Case when field = 'this' then 1 else 0 end) as Total
from YourTable
When using CASE WHEN better to use NULL than 0 in ELSE case like below
SELECT
ExistCount = SUM(CASE WHEN StockExists='T' THEN 1 ELSE NULL END) ,
TotalCount = COUNT(ID)
FROM
dbo.Items
Doing a Sum() on a column adds up the values in that column based on group by. But lets say I want to sum these values only if all the values are not null or not 0, then I need a clause which checks if any of the values is 0 before it does the sum. How can I implement such a clause?
I'm using sql server 2005.
Thanks,
Barry
Let's supose your table schema is:
myTable( id, colA, value)
Then, one approach is:
Select colA, sum(value)
from myTable
group by colA
having count( id ) = count( nullif( value, 0 ))
Notice that nullif is a MSSQL server function. YOu should adapt code to your rdbms brand.
Explanation:
count aggregate function only count not null values. Here a counting null values test.
You say that 0+2+3=0 for this case. Assuming that NULL+2+3 should also be zero:
SELECT GroupField,
SUM(Value) * MIN(CASE WHEN COALESCE(Value, 0) = 0 THEN 0 ELSE 1 END)
FROM SumNonZero
GROUP BY GroupField
The above statement gives this result
GroupField (No column name)
case1 5
case2 0
case3 0
with this test data
CREATE TABLE SumNonZero (
GroupField CHAR(5) NOT NULL,
Value INT
)
INSERT INTO SumNonZero(GroupField, Value)
SELECT 'case1', 2
UNION ALL SELECT 'case1', 3
UNION ALL SELECT 'case2', 0
UNION ALL SELECT 'case2', 2
UNION ALL SELECT 'case2', 3
UNION ALL SELECT 'case3', NULL
UNION ALL SELECT 'case3', 3
UNION ALL SELECT 'case3', 4
It makes no sense to eliminate 0 from a SUM because it wont impact the sum.
But you may want to SUM based on another field:
select FIELD, sum(
case when(OTHER_FIELD>0) then FIELD
else 0
end)
from TABLE
group by TABLE